4

c# code-

string s="おはよう";

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

Amit
  • 219
  • 2
  • 7
  • 14
  • How do you plan to send this to c++ dll? Usually the p/invoke will do the conversion for you. – Ventsyslav Raikov May 16 '12 at 12:39
  • Then you'll be using p/invoke([DLLImport]) and it should just work. – Ventsyslav Raikov May 16 '12 at 12:47
  • thats not the issue, but how to convert string to wchar in C++ – Amit May 16 '12 at 13:01
  • I don't think there's a way to marshal a C# string to a C++ `std::wstring`. You can marshal it as a `LPTStr` or possibly `LPWStr`, but those are simply arrays of characters. Show us the prototype of the function you want to call, and we can make recommendations. You might also take a look at http://stackoverflow.com/questions/7051097/return-a-stdwstring-from-c-into-c-sharp – Jim Mischel May 16 '12 at 14:07
  • Nice help @JimMischel, thanks. Is there any other way to do it, or vice versa – Amit May 17 '12 at 06:53

1 Answers1

4

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.

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351