开发者

Best way to pass char* to .Net

I want to pass a big char* from cpp to .Net (preferably using COM). What is the best way (in terms 开发者_运维问答of memory)?

If I use CComBSTR it takes a lot of memory both when creating the BSTR in CPP and especially when moving it to .Net inside the COM call.


My choice would be to marshal to String, although I've seen StringBuilders being used too if there is some post-processing such as further concats to be done.

See here for a simple example.


You can pass a StringBuilder as an input parameter and the C++ code can write into that.

From a FAQ on PInvoke:

To solve this problem (since many of the Win32 APIs expect string buffers) in the full .NET Framework, you can, instead, pass a System.Text.StringBuilder object; a pointer will be passed by the marshaler into the unmanaged function that can be manipulated. The only caveat is that the StringBuilder must be allocated enough space for the return value, or the text will overflow, causing an exception to be thrown by P/Invoke.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜