6

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();

1 Answer 1

1

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

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

6 Comments

There's nothing wrong with making fields public in structs that are used solely for P/Invoke purposes. All accessors would be trivial anyway, and this would not ever change in the future, so why write more code?
I tried that but I keep getting Method's type signature is not PInvoke compatible
Reading the Microsoft help it says "ANSI strings must be marshaled using an IntPtr and passed as an array of bytes."
@SteveM, what help? Link, please. Most likely it's for some corner case, not applicable here.
@Pavel here is the link msdn.microsoft.com/en-us/library/ms172514.aspx Also I import the DLL like this [DllImport("SomeDLL.dll", CharSet = CharSet.Ansi)] static extern ManagedStruct function( string input ); And inside the DLL the function is extern "C" UnmanagedStruct __declspec(dllexport) function( char* input ); Thanks again for your help.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.