Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

c# code-

string s="おはよう";

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

like image 771
Amit Avatar asked Oct 24 '25 18:10

Amit


1 Answers

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.

like image 118
Jim Mischel Avatar answered Oct 26 '25 08:10

Jim Mischel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!