May 4, 2012

[How to] Transfer Pointer to C/C++ DLLs

In "SomeDLL.dll", there's an entry point "GetValue" which declared as
int GetValue(char* buffer, int length)


We should import it in C# first.
[DllImport("SomeDLL.dll")]
public static extern int GetValue(IntPtr buffer, int length);


Therefore, how to use it?

using System.Runtime.InteropServices;


//initialize

int length = 24;
byte[] value = new byte[length];
IntPtr p = Marshal.AllocHGlobal(sizeof(byte) * length);
//call API
GetValue(p, length);
//retrieve value
Marshal.Copy(p, value, 0, length);
Marshal.FreeHGlobal(p);

No comments:

Post a Comment