Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'd do it with a <code>BSTR</code> since 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.</p> <p>With a <code>BSTR</code> the marshaller will take care of deallocating the <code>BSTR</code> with the right memory manager so you can safely pass it out of your C++ code.</p> <p><strong>C++</strong></p> <pre><code>#include &lt;comutil.h&gt; BSTR GetSomeText() { return ::SysAllocString(L"Greetings from the native world!"); } </code></pre> <p><strong>C#</strong></p> <pre><code>[DllImport(@"test.dll", CallingConvention = CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.BStr)] private static extern string GetSomeText(); </code></pre> <p>There is one minor drawback of the <code>BSTR</code>, namely that it carries a UTF-16 payload but your source data may well be <code>char*</code>.</p> <p>To overcome this you can wrap up the conversion from <code>char*</code> to <code>BSTR</code> like this:</p> <pre><code>BSTR ANSItoBSTR(const char* input) { BSTR result = NULL; int lenA = lstrlenA(input); int lenW = ::MultiByteToWideChar(CP_ACP, 0, input, lenA, NULL, 0); if (lenW &gt; 0) { result = ::SysAllocStringLen(0, lenW); ::MultiByteToWideChar(CP_ACP, 0, input, lenA, result, lenW); } return result; } </code></pre> <p>That's the hardest one out of the way, and now it's easy to add other wrappers to convert to <code>BSTR</code> from <code>LPWSTR</code>, <code>std::string</code>, <code>std::wstring</code> etc.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload