[英]get pointer on byte array from unmanaged c++ dll in c#
在c ++我有這樣的功能
extern "C" _declspec(dllexport) uint8* bufferOperations(uint8* incoming, int size)
我試圖從c#這樣調用它
[DllImport("MagicLib.DLL", CallingConvention = CallingConvention.Cdecl)]
//[return: MarshalAs(UnmanagedType.ByValArray)]//, ArraySubType=UnmanagedType.SysUInt)]
public static extern byte[] bufferOperations(byte[] incoming, int size);
但我得到了無法編組'返回值':無效的托管/非托管類型組合
((問題是 - 如何正確編組?感謝您閱讀我的問題
byte []是一個已知長度的.Net數組類型。 你不能編組字節*,因為.Net不知道輸出數組的長度。 你應該嘗試手動編組。 將byte []替換為byte *。 然后,這樣做:
[DllImport("MagicLib.DLL", CallingConvention = CallingConvention.Cdecl)]
public static extern byte* bufferOperations(byte* incoming, int size);
public void TestMethod()
{
var incoming = new byte[100];
fixed (byte* inBuf = incoming)
{
byte* outBuf = bufferOperations(inBuf, incoming.Length);
// Assume, that the same buffer is returned, only with data changed.
// Or by any other means, get the real lenght of output buffer (e.g. from library docs, etc).
for (int i = 0; i < incoming.Length; i++)
incoming[i] = outBuf[i];
}
}
在這種情況unsafe contexts
,您不需要使用unsafe contexts
。 只需使用IntPtr 。
[DllImport("MagicLib.DLL", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr bufferOperations(IntPtr incoming, int size);
然后你可以使用Marshal.Copy從中獲取你的字節數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.