我想通过一个字节[]
在C#中的方法需要一个的IntPtr
参数,是可能的怎么样?
I want to pass a byte[]
to a method takes a IntPtr
Parameter in C#, is that possible and how?
不知道有关获取一个IntPtr到一个数组,但你可以通过使用Mashal.Copy复制数据与非托管code使用:
Not sure about getting an IntPtr to an array, but you can copy the data for use with unmanaged code by using Mashal.Copy:
IntPtr unmanagedPointer = Marshal.AllocHGlobal(bytes.Length);
Marshal.Copy(bytes, 0, unmanagedPointer, bytes.Length);
// Call unmanaged code
Marshal.FreeHGlobal(unmanagedPointer);
另外,您可以用一个属性声明一个结构,然后用Marshal.PtrToStructure,但仍需要分配非托管内存。
Alternatively you could declare a struct with one property and then use Marshal.PtrToStructure, but that would still require allocating unmanaged memory.
编辑:同时,作为Tyalis指出的那样,你也可以使用的固定的,如果不安全code是一个选择
Also, as Tyalis pointed out, you can also use fixed if unsafe code is an option for you