c# : how to convert c# string to c++ wstring and vice-versa

3.5k views Asked by At

c# code-

string s="おはよう";

I want to send s to c++ dll, as wstring..
how to convert string to wstring in c# ?

1

There are 1 answers

0
Jim Mischel On

A std::wstring is a C++ object, allocated by the C++ runtime and having an implementation-dependent internal format. You might be able to figure out how to create one of those in a C# program and pass it to the unmanaged C++ code, but doing so would be somewhat difficult and fraught with peril. Because the internal structure of a std::wstring is implementation dependent, any change to the C++ compiler or runtime libraries break your solution.

What you're trying to do is typically done by writing an interface layer in C++ that takes an LPTStr parameter, converts it to a std::wstring, and then calls the C++ function that you wanted to call. That is, if the function you want to call is declared as:

int Foo(std::wstring p);

You would write an interface function:

int FooCaller(LPTSTR p)
{
    std::wstring str = p;
    return Foo(str);
}

And you call FooCaller from your C# program.

In short, C# can't create and pass a std::wstring, so you use a translation layer.