从C#调用C ++函数 - 奇怪的参数 [英] Call C++ function in C# from DLL - strange parameters
问题描述
我有一个函数writen在C ++与下一个标题:
I have a function writen in C++ with the next header:
void EncodeFromBufferIN(void* bufferIN,int bufferINSize, unsigned char* &bufferOUT, int &bufferOUTSize);
我已经编辑了.h和.cpp文件,在C#中导入DLL:
I've edited the .h and .cpp files like this, to be able calling the function by importing the DLL in C#:
**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#,但不知道如何传递参数的函数。
But now my problem is that I don't know how to call the function in C#. I've added the next code in C# but not sure how to pass the parameters to the function.
[DllImport("QASEncoder.dll")]
unsafe public static extern void EncodeFromBufferIN(void* bufferIN, int bufferINSize, out char[] bufferOUT, out int bufferOUTSize);
bufferIN和bufferOUT应该是字符串,但是如果我像这样调用函数:
The bufferIN and bufferOUT should be strings but if I'm calling the function like this:
public string prepareJointsForQAS()
{
string bufferIN = "0 0 0 0 0";
char[] bufferOUT;
int bufferOUTSize;
EncodeFromBufferIN(bufferIN, bufferIN.Length, bufferOUT, bufferOUTSize);
}
我得到这个错误:最好的重载方法matrch for ...一些无效参数。那么如何传递参数呢?
I get this error: "The best overloaded method matrch for ... has some invalid arguments". So how should the parameters be passed?
推荐答案
Marshalling最适合使用C Style调用。所以最好在你的公共接口上使用
pure C。
如果将本机代码更改为
Marshalling works best with C Style calls. So it is best to use pure C on your public interface. If it is at all feasible to change the native code to
void EncodeFromBufferIN(
unsigned char* bufferIN,
int bufferINSize,
unsigned char* bufferOUT,
int* bufferOUTSize);
$ b
Then the call in C# can be thus
[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);
<乱。
This way you can avoid memory allocations in unmanaged code which (although feasible) can get messy.
希望这会让你走。
这篇关于从C#调用C ++函数 - 奇怪的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!