網頁

2015年10月20日 星期二

C# use Unmanaged memory to call function

Last Update: 2015/10/21 00:04+08



Intro




Content

C++ code
extern "C" __declspec(dllexport) int myfunc(BYTE* data, int datasize){
 int rs = 0;
 for (int idx = 0; idx < datasize; idx++){
  rs += idx;
  data[idx] = idx;
 }
 return rs;
}



這裡提供兩種使用Unmanager memory的方法, 分別使用了Marshal和PinnedObject
[DllImport(@"../../../Debug/PinnedObjLib.dll", EntryPoint = "myfunc", CallingConvention = CallingConvention.Cdecl)]
static extern int myfunc(IntPtr ptr, int datasize);

static void Main(string[] args)
{
 way_marshal();
 way_pinnedObj();

 Console.ReadKey();
}



Marshal
static void way_marshal()
{
 Console.WriteLine("Marshal");

 int datasize = 16;
 IntPtr ptr = Marshal.AllocHGlobal(datasize);

 Console.WriteLine(myfunc(ptr, datasize));
 byte[] data = new byte[datasize];
 Marshal.Copy(ptr, data, 0, datasize);
 for (int idx = 0; idx < datasize; idx++) { Console.WriteLine(data[idx]); }

 Marshal.FreeHGlobal(ptr);
}



PinnedObject
static void way_pinnedObj()
{
 Console.WriteLine("PinnedObject");

 int datasize = 16;
 byte[] data = new byte[datasize];

 GCHandle gHdl = GCHandle.Alloc(data, GCHandleType.Pinned);

 Console.WriteLine(myfunc(gHdl.AddrOfPinnedObject(), datasize));
 for (int idx = 0; idx < datasize; idx++) { Console.WriteLine(data[idx]); }

 gHdl.Free();
}

沒有留言:

張貼留言