Hi there!
I have a COM server at the lowest level of C++, closer to C. I have reached to connect it with a DLL in C#, sending strings from C# and getting BSTRs in COM. When I try to send backwords, i.e. BSTRs from C++ I'm having strange characters got in C#. Since the .net marshalling goes fine from C# to COM, what's the corresponding conversion method (or attribute) for "what I receive in C# from COM" to transform in the right string in C#? Thanks!
AlanPosted Aug 25, 2008, 1:57 PM
I'd try applying the following attribute to the string return type of the COM method or property 'get':
[return : MarshalAs(UnmanagedType.BStr)]
AlanPosted Aug 26, 2008, 3:17 PM
TBH I'm better on P/Invoke than I am on COM interop though I do know a bit about the latter as well.
By default, .NET strings are marshalled by COM Interop to LPTSTR in C++ and, vice versa, and so you have to explicitly marshal any other type of unmanaged string (including BSTR) to and from a .NET string using the MarshalAs attribute.
There's no particular problem in inheriting from IUnknown or IDispatch but, if you inherit from the latter, you have to mark the C# interface declaration with the InterfaceType attribute.
Properties in C# are mapped to 'get' and 'set' methods by the CLR but it's a good idea to use methods in your own C# interface declaration code to be as close as possible to the C++ functions.
OparitiPosted Aug 26, 2008, 6:08 AM
Thanks. It doesn't work that way (on the contrary, it worked when I had to declare through BStr marshaling when I passed from C# tlb to the COM object in C++).
In fact, as I see you are expert in COM interop, could you please recommand a safe way to pass strings back and forth between C#/.net and C++/COM? The problem I'm having is that all strings in .net are Unicode and I'm quite lost (as info) in doing the passing. I'm using an usual interface in C# (no inheritance with IUnknown or IDisposable - should I do it?) and passing strings through methods (I didn't try through property since I want to keep the C++ as close as possible to C). Appreciate your hints.