我有一个指向Windows GDI函数分配的数组的指针。
我可以使用Marshal类将数据复制进出,但是对于我所需要的来说这很慢。如何设置托管代码可以获取并设置为正常值的数组,以更新非托管指针处的数据?
我可以使用C#还是需要使用C ++ / CLI?
编辑:目的是读取和写入数组以从任何.NET语言(包括VB.NET)更新图像。
您可以在C#中使用代码的unsafe
部分执行指针操作。
尝试一下:
using System;
class HelloWorld {
static void Main()
{
var arr = new byte[3]{1,2,3};
var ptr = GetArrayPointer(ref arr);
Console.WriteLine("pointer="+ptr);
SetValue(ptr, 2, 8);
PrintArr(arr);
}
public static unsafe long GetArrayPointer(ref byte[] array)
{
fixed (byte* ptr = array)
{
return ((IntPtr)ptr).ToInt64();
}
}
public static unsafe void SetValue(long ptrValue, int index, byte newValue)
{
var ptr = new IntPtr(ptrValue);
byte* byteptr = (byte*)ptr;
byte* indexedPtr = byteptr + (index * sizeof(byte));
Console.WriteLine("old value="+(*indexedPtr));
(*indexedPtr) = newValue;
}
public static void PrintArr(byte[] arr){
for(var i=0;i<arr.Length;i++){
Console.Write(arr[i] + ",");
}
}
}