2

I have a C++ dll that has a function that returns a c string and I have a C# program that calls this function and returns the data to a C# string. Here's what I mean

__declspec(dllexport) const char* function (const char* str) {
        std::string stdString( str );
        std::cout << stdString.c_str() << std::endl; // this prints fine, no data loss
        return stdString.c_str();
}

And here's the C# code

  [DllImport("MyDLL.dll")]
  public static extern string function(string data);

  string blah = function("blah");
  Console.WriteLine(blah); // doesn't print anything... 

When I look into the locals it says variable 'blah' is equal to "".

What happened to the data?

3
  • 2
    It got destroyed together with stdString. Commented Dec 7, 2011 at 2:02
  • C#'s string is not equivalent to const char*. Commented Dec 7, 2011 at 2:02
  • What would I use to return to a C# string? Commented Dec 7, 2011 at 2:02

1 Answer 1

4

Your C++ code is broken. You are returning a pointer to a local variable. It no longer exists after the function returns. This tends to work by accident in a C++ program but is strong Undefined Behavior. It cannot possibly work in an interop scenario, the pinvoke marshaler's use of the stack will overwrite the string.

A declaration that could work:

 void function (const char* str, char* output, size_t outputLength)

Use a StringBuilder in the [DllImport] declaration for the output argument and pass an initialized one with sufficient Capacity.

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

2 Comments

How do I convert my std::string values to char* values?
You already did in your original snippet. But you have to copy the string to output. Use strcpy_s().

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.