从C#中不受管理的C DLL获取字节数组上的指针
作者:互联网
在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];
}
}
标签:c,dll,unmanaged,marshalling,c-2 来源: https://codeday.me/bug/20191012/1897223.html