问题
I have a function writen in C++ with the next header:
void EncodeFromBufferIN(void* bufferIN,int bufferINSize, unsigned char* &bufferOUT, int &bufferOUTSize);
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
}
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);
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);
}
I get this error: "The best overloaded method matrch for ... has some invalid arguments". So how should the parameters be passed?
回答1:
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);
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.
Hope this gets you going.
回答2:
A few corrections that worked for me:
string inStr = "Value to pass";
int inSize = inStr.Length;
StringBuilder outStr = new StringBuilder(255);
int outSize = 255;
EncodeFromBufferIN(inStr, inSize, outStr, ref outSize);
regards.
来源:https://stackoverflow.com/questions/12618747/call-c-function-in-c-sharp-from-dll-strange-parameters