将C中的字节数组转换为C#

时间:2016-04-26 16:24:27

标签: c# c marshalling unmanaged

我需要从C#调用以下C函数:

__declspec(dllexport) int receive_message(char* ret_buf, int buffer_size);

我在C#方面声明了以下内容:

[DllImport("MyCLibrary", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto, EntryPoint = "receive_message")]
public static extern int ReceiveMessage([MarshalAs(UnmanagedType.LPStr)]StringBuilder retBuf, int bufferSize);

我正在调用这样的函数:

StringBuilder sb = new StringBuilder();
int len = ReceiveMessage(sb, 512);

这对我的初始测试工作正常,我收到“字符串”消息。但是,现在我想接收压缩消息(字符/字节数组)。问题是字符/字节数组将有0并将终止字符串,所以我不回复整个消息。我有什么想法可以重构来获取字节数组吗?

1 个答案:

答案 0 :(得分:2)

在jdweng的帮助下,我已将声明更改为:

[DllImport("MyCLibrary", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto, EntryPoint = "receive_message")]
public static extern int ReceiveMessage(IntPtr retBuf, int bufferSize);

并且,我在C#端分配和释放内存以及编组数据。

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);
}