// MarshalANSI1.cpp
// compile with: /clr
#include <iostream>
#include <stdio.h>
using namespace std;
using namespace System;
using namespace System::Runtime::InteropServices;
#pragma unmanaged
void NativeTakesAString(
const char* p) {
printf_s("(native) received '%s'\n", p);
}
#pragma managed
int main() {
String^ s = gcnew String("sample string");
IntPtr ip = Marshal::StringToHGlobalAnsi(s);
const char* str = static_cast<
const char*>(ip.ToPointer());
Console::WriteLine("(managed) passing string
![](http://www.cppblog.com/Images/dot.gif)
");
NativeTakesAString( str );
Marshal::FreeHGlobal( ip );
}
下面的示例演示访问由非托管函数调用的托管函数中的 ANSI 字符串所需的数据封送处理。托管函数在接收到本机字符串时,可以直接使用该字符串,也可以按所示方式使用 PtrToStringAnsi 方法将其转换为托管字符串。
复制代码
// MarshalANSI2.cpp
// compile with: /clr
#include <iostream>
#include <vcclr.h>
using namespace std;
using namespace System;
using namespace System::Runtime::InteropServices;
#pragma managed
void ManagedStringFunc(
char* s) {
String^ ms = Marshal::PtrToStringAnsi(static_cast<IntPtr>(s));
Console::WriteLine("(managed): received '{0}'", ms);
}
#pragma unmanaged
void NativeProvidesAString() {
cout << "(native) calling managed func
![](http://www.cppblog.com/Images/dot.gif)
\n";
ManagedStringFunc("test string");
}
#pragma managed
int main() {
NativeProvidesAString();
}