例:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
[DllImport("kernel32.dll")]
public static extern void CopyMemory(byte[] Destination, SS[] add, int Length); [DllImport("kernel32.dll")]
public static extern void CopyMemory(SS[] Destination, Byte[] Source, int Length); public struct SS
{
public uint i;
public byte k;
public uint j;
}
public byte[] ii = new byte[800];
public byte[] uu = new byte[800]; private void Form1_Load(object sender, EventArgs e)
{ } private void button2_Click(object sender, EventArgs e)
{
SS[] ss = new SS[1];
ss[0].i = 1334566745;
ss[0].k = 1;
ss[0].j = 3456789012;
CopyMemory(ii, ss, 12); //ii的值正确,是ss里的内容 SS[] sss = new SS[1];
CopyMemory(sss, ii, 12); //sss里的内容全是0,不知道哪错了.
} }
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
[DllImport("kernel32.dll")]
public static extern void CopyMemory(byte[] Destination, SS[] add, int Length); [DllImport("kernel32.dll")]
public static extern void CopyMemory(SS[] Destination, Byte[] Source, int Length); public struct SS
{
public uint i;
public byte k;
public uint j;
}
public byte[] ii = new byte[800];
public byte[] uu = new byte[800]; private void Form1_Load(object sender, EventArgs e)
{ } private void button2_Click(object sender, EventArgs e)
{
SS[] ss = new SS[1];
ss[0].i = 1334566745;
ss[0].k = 1;
ss[0].j = 3456789012;
CopyMemory(ii, ss, 12); //ii的值正确,是ss里的内容 SS[] sss = new SS[1];
CopyMemory(sss, ii, 12); //sss里的内容全是0,不知道哪错了.
} }
}
再说了.suruct转byte数组都好使,为什么反过来就不行?
Marshal.ReadByte
Marshal.WriteByte
可以实现功能CopyMemory
2.我以前写了个实现类似功能的把一个4位的INT或者LONG转成ARRAY或者反转可以参考下
至于你要转多少位自己改改就好//转BYTE[]
static byte[] CopyMemory(byte[] arr,int arr_index,long input) //lenth = 4
{
if(arr_index+4 > arr.Length)
{
// 不能执行
return arr;
} arr[arr_index+3]=(byte)((input & 0xff000000) >> 24);
arr[arr_index+2]=(byte)((input & 0x00ff0000) >> 16);
arr[arr_index+1]=(byte)((input & 0x0000ff00) >> 8);
arr[arr_index]=(byte)(input & 0x000000ff); arr[arr_index] &= 0xff;
arr[arr_index+1] &= 0xff;
arr[arr_index+2] &= 0xff;
arr[arr_index+3] &= 0xff; return arr;
}//转LONG
static long CopyMemory(long Out,byte[] arr,int arr_index)
{
if(arr_index+4 > arr.Length)
{
return Out;
//不能执行
} long x1 = arr[arr_index+3] << 24;
long x2 = arr[arr_index+2] << 16;
long x3 = arr[arr_index+1] << 8;
long x4 = arr[arr_index]; long o = x1 | x2 | x3 | x4;
o &= 0xffffffff;
return o;
}