Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Marshal C++ "string" class in C# P/Invoke

I have a function in a native DLL defined as follows:

#include <string>
void SetPath(string path);

I tried to put this in Microsoft's P/Invoke Interop Assistant, but it chokes on the "string" class (which I think is from MFC?).

I have tried marshaling it as a variety of different types (C# String, char[], byte[]) but every time I either get a NotSupportedException or a Native Assembly Exception (depending on what marshaling I tried).

As anyone ever done Native/Managed Interop where the native string class is used? Is there any way to Marshal this? Am I going to have to write my own Marshaler?

like image 694
Adam Haile Avatar asked Oct 01 '08 16:10

Adam Haile


People also ask

What is marshal string?

Strings are marshalled as a COM-style BSTR type or as a null-terminated string (a character array that ends with a null character). The characters within the string can be marshalled as Unicode (the default on Windows systems) or ANSI.

What is Marshal class in C#?

This class offers a collection of static methods for working with unmanaged memory and converting managed types to unmanaged types. Unless you are developing specialized code for marshaling types between managed and unmanaged code, you probably do not need to use any of these methods.

What is Marshal C++?

Most generally: marshalling is the process of transforming the. memory representation of objects to a form suitable for storage. or transmission. Used here somewhat interchangeably with serialization: converting an object into a byte stream that can later be.

What is marshalling and why do we need it?

In computer science, marshalling or marshaling (US spelling) is the process of transforming the memory representation of an object into a data format suitable for storage or transmission. It is typically used when data must be moved between different parts of a computer program or from one program to another.


2 Answers

Looks like you're trying to use the C++ standard library string class. I doubt that will be easy to Marshal. Better to stick with a char * and Marshal as StringBuilder. That's what I usually do. You'll have to add a wrapper that generates the C++ string for you.

like image 189
Andrew Queisser Avatar answered Oct 09 '22 15:10

Andrew Queisser


The PInvoke interop assistant only supports C not C++. Unfortunately the MFC String class (CString I believe?) is C++ and won't work through the assistant. Instead try using the following

void SetPath(__in const WCHAR* path);
like image 42
JaredPar Avatar answered Oct 09 '22 17:10

JaredPar