Reputation: 13
c code
extern "C" __declspec(dllexport) int export(LPCTSTR inputFile, string &msg)
{
msg = "haha"
}
c# code
[DllImport("libXmlEncDll.dll")]
public static extern int XmlDecrypt(StringBuilder inputFile, ref Stringbuilder newMsg)
}
I got an error when I try to retrieve the content of newMsg saying that I'm trying to write to a protected memory area.
What is the best way to retrieve the string from c to c#. Thanks.
Upvotes: 1
Views: 1332
Reputation: 13
Hans,
It works, thanks a lot. By the way, I found a problem at C# code. string inputFile only passes the first character. I made a modification by marshalling it
[DllImport("libXmlEncDll.dll")]
public static extern void test(string file, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder msg, int msgLen);
Again, thank you.
Upvotes: 0
Reputation: 942368
Using DLLs with exports that take C++ classes as their argument is dangerous even in C++. It is impossible to interop with C#. You cannot use the same memory allocator and you can't call the constructor and destructor. Not to mention that your C++ code isn't valid, it doesn't actually return the string.
Use a C string instead. Make it look like this:
extern "C" __declspec(dllexport)
void __stdcall XmlDecrypt(const wchar_t* inputFile, wchar_t* msg, int msgLen)
{
wcscpy_s(msg, msgLen, L"haha");
}
[DllImport("libXmlEncDll.dll", CharSet = CharSet.Auto)]
public static extern void XmlDecrypt(string inputFile, StringBuilder msg, int msgLen)
...
StringBuilder msg = new StringBuilder(666);
XmlDecrypt(someFile, msg, msg.Capacity);
string decryptedText = msg.ToString();
Some notes with these code snippets:
Upvotes: 4