簡體   English   中英

將字節數組從C導入C#

[英]Getting byte array from C into C#

我有以下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);

這對我最初收到“字符串”消息的測試很有效。 但是,現在我想接收打包的消息(字符/字節數組)。 問題是chars / bytes數組將為0,並且將終止字符串,因此我不會找回整個消息。 有什么想法可以重構以獲取字節數組嗎?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM