I am using Pinvoke for Interoperability between Native(C++) code and Managed(C#) code. What i want to achieve is get some text from native code into my managed code. For this i try lot lot of things,e.g passing string/stringbuilder by ref, using [IN] and [OUT], Marshaling to LPSTR, returning string from function etc. but nothing works in my case. Any help with some small code would be highly appreciated.
I am using Pinvoke for Interoperability between Native(C++) code and Managed(C#) code. What i
Share
I’d do it with a
BSTRsince it means you don’t have to call into native twice per string, once to get the length and then once to get the contents.With a
BSTRthe marshaller will take care of deallocating theBSTRwith the right memory manager so you can safely pass it out of your C++ code.C++
C#
There is one minor drawback of the
BSTR, namely that it carries a UTF-16 payload but your source data may well bechar*.To overcome this you can wrap up the conversion from
char*toBSTRlike this:That’s the hardest one out of the way, and now it’s easy to add other wrappers to convert to
BSTRfromLPWSTR,std::string,std::wstringetc.