Reputation: 16845
I have the following C++ function:
int my_func(char* error) {
// Have access here to an Exception object called `ex`
strcpy(error, ex.what());
return 0;
}
I am PInvoking it like this in C#:
[DllImport("pHash.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int my_func(
[MarshalAs(UnmanagedType.LPStr)]
StringBuilder error);
And using like this in the code (always C# of course):
StringBuilder error = new StringBuilder();
int returnValue = my_func(error);
If I run this, the program crashes terribly (meaning that is crashes with no exception. Just closes, that's it). What am I doing wrong?
Upvotes: 0
Views: 379
Reputation: 109567
The question here is: How does your code know how large the string buffer should be?
Normally you'd have some way of finding out. In the absence of this information, the only thing you can do is to initialise the StringBuilder
to be as large as the largest string you expect, before calling the function.
For example:
StringBuilder error = new StringBuilder(1024); // Assumes 1024 chars max.
Your code is passing a StringBuilder
with a default capacity, which is (I think) 16, so any string larger than that will cause a crash.
Upvotes: 2