I'm passing a byte[] to a function accepting an unsigned char*
One way I can do this is to pass an IntPtr, and allocate/deallocate memory in managed code as follows:
in C++ DLL
extern "C" { __declspec(dllexport) void __stdcall Foo(int length, unsigned char** message); }in C#
[DllImport(@"MyDll.dll"] public static extern void Foo(int length, ref IntPtr msg); byte[] msg = new byte[] {0,1,2,3}; IntPtr ip = Marshal.AllocHGlobal(msg.Length); Marshal.Copy(msg, 0, ip, msg.Length); UnmanagedCode.Foo(msg.Length, ref ip); Marshal.FreeHGlobal(ip);
I can also do this:
in C++ DLL
extern "C" { __declspec(dllexport) void __stdcall Foo(int length, unsigned char* message); }in C#
[DllImport(@"MyDll.dll"] public static extern void Foo(int length, byte[] msg); byte[] msg = new byte[] {0,1,2,3}; UnmanagedCode.Foo(msg.Length, msg);
Both implemntations work well, but in my second example, how is the memory (for the unsigned char* message) managed. I'm guessing that memory is allocated when the call to Foo is made, and deallocated when it returns (so it behaves much like the first example) - is this correct?
Thanks
ref ipin the first example. You can't possibly be changing the value ofip. In the second example,unsigned char message[]reads much better. Finally, if you are passing IP addresses around, a struct would be the way to go—no need for a length parameter.