Yaron Naveh
Yaron Naveh

Reputation: 24436

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.

Upvotes: 1

Views: 331

Answers (2)

NT_
NT_

Reputation: 2670

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.

Upvotes: 2

Ed Swangren
Ed Swangren

Reputation: 124800

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.

Upvotes: 0

Related Questions