从DLL中调用C#中的C ++函数 - 奇怪的参数

时间:2012-09-27 09:57:44

标签: c# c++ dll com

我在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);
}

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

2 个答案:

答案 0 :(得分:5)

编组在C Style调用中效果最佳。所以最好使用 公共接口上的纯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);

这样可以避免非托管代码中的内存分配 哪个(虽然可行)可能会变得混乱。

希望这能让你前进。

答案 1 :(得分:1)

一些对我有用的更正:

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

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

问候。