I am trying to return a string from a c++ dll export function. I am calling this function from c#. I have seen a lot of examples on the internet and I am really confused what to do.
My c++ code to export function:
extern "C" __declspec(dllexport) char* __cdecl getDataFromTable(char* tableName)
{
std::string st = getDataTableWise(statementObject, columnIndex);
printf(st.c_str());
char *cstr = new char[st.length() + 1];
strcpy(cstr, st.c_str());
return cstr;
}
When I try to call this function from c#:
[DllImport("\\SD Card\\ISAPI1.dll")]
private static extern string getDataFromTable(byte[] tablename);
static void Main(string[] args)
{
string str = getDataFromTable(byteArray);
Console.writeLine(str);
}
I got an error while calling it. I am creating this for WinCE 6.0
EDITED------------------------
is there something like, i can pass a empty buffer to c++ from c# and c++ function will fill the data and i can reuse it in C#
I have had this problem too, recently, and though I have a solution for you, sadly I can't really explain it. I haven't found a sound explanation yet.
my c++ code for retrieving a string is:
extern "C" { __declspec(dllexport) void __GetValue__(char* str, int strlen); }
and my C# code:
[DllImport("MyDLL.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern void __GetValue__(StringBuilder str, int strlen);
So as you can see, instead of returning a value, you can supply a string (by using StringBuilder) and let C++ fill in the data like:
void __GetValue__(char* str, int strlen) {
std::string result = "Result";
result = result.substr(0, strlen);
std::copy(result.begin(), result.end(), str);
str[std::min(strlen-1, (int)result.size())] = 0;
}
And for completeness the C# code to request the string:
public String GetValue() {
StringBuilder str = new StringBuilder(STRING_MAX_LENGTH);
__GetValue__(str, STRING_MAX_LENGTH);
return str.ToString();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With