Reputation: 3218
I have the following C function that I need to call from C#:
__declspec(dllexport) int receive_message(char* ret_buf, int buffer_size);
I've declared the following on the C# side:
[DllImport("MyCLibrary", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto, EntryPoint = "receive_message")]
public static extern int ReceiveMessage([MarshalAs(UnmanagedType.LPStr)]StringBuilder retBuf, int bufferSize);
I'm calling the function like so:
StringBuilder sb = new StringBuilder();
int len = ReceiveMessage(sb, 512);
This works fine with my initial tests where I was receiving "string" messages. But, now I want to receive packed messages (array of chars/bytes). The problem is that the array of chars/bytes will have 0s and will terminate the string so I don't get back the whole message. Any ideas how I can refactor to get array of bytes back?
Upvotes: 1
Views: 589
Reputation: 3218
With jdweng help, I've changed the declaration to:
[DllImport("MyCLibrary", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto, EntryPoint = "receive_message")]
public static extern int ReceiveMessage(IntPtr retBuf, int bufferSize);
And, I'm allocating and freeing the memory on the C# side along with marshalling the data.
IntPtr pnt = Marshall.AllocHGlobal(512);
try
{
int len = ReceiveMessage(pnt, 512);
...
byte[] bytes = new byte[len];
Marshal.Copy(pnt, bytes, 0, len);
...
}
finally
{
Marshal.FreeHGlobal(pnt);
}
Upvotes: 2