DevDevDev
DevDevDev

Reputation: 5177

Marshalling a struct containing c-strings

I have a C++ struct

struct UnmanagedStruct
{
   char* s;
};

and a C# struct

struct ManagedStruct {
   string s;
}

How can I marshal the UnmanagedStruct? Do I need to use a StringBuilder?

the C++ library exposes UnmanagedStruct getStruct();

Upvotes: 6

Views: 2959

Answers (1)

Sam Harwell
Sam Harwell

Reputation: 100029

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).

Upvotes: 1

Related Questions