Search code examples
c#c++stringcominterop

Convert C# string to C++ WCHAR* over COM


I have a COM local server (implemented in C++) which I am trying to call from C# code. The method that's giving me trouble looks like this:

HRESULT Foo([in] const WCHAR* bar);

The parameter shows up in on the C# side as a ref ushort, but I want to pass a string to the method, not a number. How can I make this method accept a string from C#?

The C# is pretty simple:

IFooService service = new IFooService();
service.Foo("blah blah");

I see other answers which describe DllImporting the function and then using [MarshalAs(UnmanagedType.LPWStr)] on the parameter, but since the COM server is running as a local server (meaning it's a standalone exe instead of a dll), and it's part of an interface, I don't think I can DllImport it. Do I need to do something with the server's proxy dll instead?


Solution

  • It looks like there are at least two solutions to this problem.

    1. Add the string attribute to the parameter in the IDL to treat the pointer as a string, so this:

      HRESULT Foo([in] const WCHAR* bar);
      

      becomes this:

      HRESULT Foo([in, string] const WCHAR* bar);
      

      Then, a string can be passed to the method from C#.

    2. Follow the instructions at http://www.moserware.com/2009/04/using-obscure-windows-com-apis-in-net.html and use the aptly-named ComImport attribute to declare the interface and prefix the string parameters with [MarshalAs(UnmanagedType.LPWStr)].

    I went with #1 since it is the simplest and doesn't involve adding a bunch of extra code to to the client.