Pass BSTR from C++ to C#
I have C# project "X" ,I have exposed methods in it to the C++ project "Y".
X has method signature as follows -
public void WriteInformation(string sInfo)
{
m_logger.ErrorInfo("{0}", sInfo);
}
As I am exporting it to a C++ using .TLB file I checked declaration of this method in .tlh fi开发者_StackOverflowle which generates on #import of .tlb file.
virtual HRESULT __stdcall WriteInformation ( /*[in]*/ BSTR sMsg ) = 0;
I am calling this method in C++ project and passsing argument as follows -
oLog->WriteInformation(BSTR("Info write successful"));
Issue here is the string passed from C++ always becomes garbage or null , I debugged it and I can see value of sInfo is always garbage or null.
Please let me know what method should be followed to pass string from C++ to C#.
You try to pass an ANSI string in place of BSTR. BSTR must be a wide character string. Also you shouldn't pass a string literal, you should properly allocate a BSTR using SysAllocString()
(or better yet) a wrapper class like ATL::CComBSTR
or _bstr_t
. Btw _bstr_t
has a constructor that will accept const char*
and do the ANSI->UTF16 conversion for you.
I dont think its possible to interact with C++ and C# directly. I had interacted using a C++/CLI wrapper.
精彩评论