This topic demonstrates one facet of C++ interoperability. For more information, see Using C++ Interop (Implicit PInvoke).
The following code examples use the
This topic demonstrates how Unicode strings can be passed from a managed to an unmanaged function, and vice versa. For interoperating with other strings types, see the following topics:
Example
To pass a Unicode string from a managed to an unmanaged function, the PtrToStringChars function (declared in Vcclr.h) can be used to access in the memory where the managed string is stored. Because this address will be passed to a native function, it is important that the memory be pinned with
В | ![]() |
---|---|
// MarshalUnicode1.cpp // compile with: /clr #include <iostream> #include <stdio.h> #include <vcclr.h> using namespace std; using namespace System; using namespace System::Runtime::InteropServices; #pragma unmanaged void NativeTakesAString(const wchar_t* p) { printf_s("(native) recieved '%S'\n", p); } #pragma managed int main() { String^ s = gcnew String("test string"); pin_ptr<const wchar_t> str = PtrToStringChars(s); Console::WriteLine("(managed) passing string to native func..."); NativeTakesAString( str ); } |
The following example demonstrates the data marshaling required to access a Unicode string in a managed function called by an unmanaged function. The managed function, on receiving the native Unicode string, converts it to a managed string using the
В | ![]() |
---|---|
// MarshalUnicode2.cpp // compile with: /clr #include <iostream> using namespace std; using namespace System; using namespace System::Runtime::InteropServices; #pragma managed void ManagedStringFunc(wchar_t* s) { String^ ms = Marshal::PtrToStringUni((IntPtr)s); Console::WriteLine("(managed) recieved '{0}'", ms); } #pragma unmanaged void NativeProvidesAString() { cout << "(unmanaged) calling managed func...\n"; ManagedStringFunc(L"test string"); } #pragma managed int main() { NativeProvidesAString(); } |