从c#中的非托管c ++ dll获取字节数组的指针 [英] get pointer on byte array from unmanaged c++ dll in c#

查看:165
本文介绍了从c#中的非托管c ++ dll获取字节数组的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

c ++中有这样的功能

  externC_declspec(dllexport)uint8 * bufferOperations(uint8 * incoming,int大小)

我正在尝试从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不知道输出数组的长度,应该尝试手动编组将字节[]替换为字节*,然后执行以下操作:

  [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);
//假设返回相同的缓冲区,只有数据更改。
//或任何其他意味着获得真正的输出缓冲区长度(例如,从图书馆文件等)。 (int i = 0; i< incoming.Length; i ++)
incoming [i] = outBuf [i];

}
}


in c++ I have such function

extern "C" _declspec(dllexport) uint8* bufferOperations(uint8* incoming, int size)

I am trying to call it from c# like this

[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. You can't marshal byte* to it, because .Net does not know the length of output array. You should try manual marshalling. Replace byte[] with 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];
    }
}

这篇关于从c#中的非托管c ++ dll获取字节数组的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆