[英]get pointer on byte array from unmanaged c++ dll in c#
in c++ I have such function 在c ++我有这样的功能
extern "C" _declspec(dllexport) uint8* bufferOperations(uint8* incoming, int size)
I am trying to call it from c# like this 我试图从c#这样调用它
[DllImport("MagicLib.DLL", CallingConvention = CallingConvention.Cdecl)]
//[return: MarshalAs(UnmanagedType.ByValArray)]//, ArraySubType=UnmanagedType.SysUInt)]
public static extern byte[] bufferOperations(byte[] incoming, int size);
But I get the Cannot marshal 'return value': Invalid managed/unmanaged type combination 但我得到了无法编组'返回值':无效的托管/非托管类型组合
((( The question is - how to marshal this correctly? Thanks for reading my question ((问题是 - 如何正确编组?感谢您阅读我的问题
byte[] is a .Net array type with known length. byte []是一个已知长度的.Net数组类型。 You can't marshal byte* to it, because .Net does not know the length of output array. 你不能编组字节*,因为.Net不知道输出数组的长度。 You should try manual marshalling. 你应该尝试手动编组。 Replace byte[] with byte*. 将byte []替换为byte *。 Then, do like this: 然后,这样做:
[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];
}
}
You don't need to use unsafe contexts
in this case. 在这种情况unsafe contexts
,您不需要使用unsafe contexts
。 Just use IntPtr . 只需使用IntPtr 。
[DllImport("MagicLib.DLL", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr bufferOperations(IntPtr incoming, int size);
And then you can use Marshal.Copy to get your byte-array from it. 然后你可以使用Marshal.Copy从中获取你的字节数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.