// 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 );
}
下面的示例演示在非托管函数调用的托管函数中访问 Unicode 字符串时需要的数据封送处理。一旦托管函数接收到本机 Unicode 字符串,就会使用 PtrToStringUni 方法将其转换为托管字符串。
复制代码
// 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();
}