Edit & Correction: For return values of p/invoke calls, the "normal" method doesn't work. I was so used to the normal, ref
, and out
behaviors related to method parameters that I assumed return values would work in a similar fashion. Here is the link for a solution to the return value problem:
PInvoke error when marshalling struct with a string in it
You only need to use a StringBuilder
if you are passing the struct to the C++ method as a byref parameter and the string is a buffer that the method will alter. For a return value, you just need to specify the type of string, which in this case is:
struct ManagedStruct
{
[MarshalAs(UnmanagedType.Lpstr)]
string s;
}
Rememer to add a property to expose the string, since s
is private here (which is OK, fields should be private).