0

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?

3
  • 1
    Matthew's answer seems correct. But for your next question: please tell us at least the error message. "Crashes terribly" is not as good a hint as an exception message. Commented Jun 30, 2016 at 7:59
  • There is no exception, that is the problem. The program exits and that's it... Commented Jun 30, 2016 at 8:06
  • The interface of this function is irredeemably broken. You cannot protect against buffer overruns. You have to make the caller pass the length of the buffer, and then ensure you do not copy beyond the end of the buffer. Commented Jun 30, 2016 at 8:35

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.