2

我有一个用 C++ 编写的函数,带有下一个标题:

void EncodeFromBufferIN(void* bufferIN,int bufferINSize, unsigned char*  &bufferOUT, int &bufferOUTSize);

我已经像这样编辑了 .h 和 .cpp 文件,以便能够通过在 C# 中导入 DLL 来调用该函数:

**EncodeFromBufferIN.h**
extern "C" {
     __declspec(dllexport) void EncodeFromBufferIN(void* bufferIN, int bufferINSize, unsigned char*  &bufferOUT, int &bufferOUTSize);
}
**EncodeFromBufferIN.cpp**
extern void EncodeFromBufferIN(void* bufferIN, int bufferINSize, unsigned char*  &bufferOUT, int &bufferOUTSize){
    // stuff to be done
}

但现在我的问题是我不知道如何在 C# 中调用该函数。我在 C# 中添加了下一个代码,但不确定如何将参数传递给函数。

[DllImport("QASEncoder.dll")]
        unsafe public static extern void EncodeFromBufferIN(void* bufferIN, int bufferINSize, out char[] bufferOUT, out int bufferOUTSize);

bufferIN 和 bufferOUT 应该是字符串,但如果我这样调用函数:

public string prepareJointsForQAS()
{
   string bufferIN = "0 0 0 0 0";
   char[] bufferOUT;
   int bufferOUTSize;
   EncodeFromBufferIN(bufferIN, bufferIN.Length, bufferOUT, bufferOUTSize);
}

我收到此错误:“...的最佳重载方法匹配有一些无效参数”。那么应该如何传递参数呢?

4

2 回答 2

5

编组最适合 C 风格的调用。所以最好在你的公共接口上使用纯 C。如果将本机代码更改为

void EncodeFromBufferIN(
    unsigned char* bufferIN, 
    int bufferINSize, 
    unsigned char* bufferOUT,     
    int* bufferOUTSize);

那么C#中的调用可以这样

[DllImport("QASEncoder.dll")]
public static extern void EncodeFromBufferIN(
    String bufferIN, 
    int bufferINSize, 
    StringBuilder bufferOUT, 
    ref int bufferOUTSize);

String inStr = new String(255);
int inSize = 255;
// make an educated estimate for the output size 
// and preallocate in C# (I am guessing 255)
StringBuilder outStr = new StringBuilder(255);
int outSize = 255;

EncodeFromBufferIN(inStr, inSize, outStr, outSize);

这样,您可以避免非托管代码中的内存分配(尽管可行)会变得混乱。

希望这能让你继续前进。

于 2012-09-27T11:54:47.363 回答
1

一些对我有用的更正:

        string inStr = "Value to pass";
        int inSize = inStr.Length;
        StringBuilder outStr = new StringBuilder(255);
        int outSize = 255;

        EncodeFromBufferIN(inStr, inSize, outStr, ref outSize);

问候。

于 2013-05-09T19:06:01.793 回答