微软提供了msclr::interop用来实现托管类型和本地类型的转化。
示例代码如下:
#include <stdlib.h>
#include <string.h>
#include <msclr/marshal.h>
using namespace System;
using namespace msclr::interop;
int main() {
const char* message = "Test String to Marshal";
wchar_t *wstr = L"Hello";
String^ result;
result = marshal_as<String^>( wstr );
return 0;
}
但是在转换过程中有的需要context,有的不需要context。
依据如下:(摘自msdn)
Marshaling requires a context only when you marshal from managed to native data types and the native type you are converting to does not have a destructor for automatic clean up. The marshaling context destroys the allocated native data type in its destructor. Therefore, conversions that require a context will be valid only until the context is deleted. To save any marshaled values, you must copy the values to your own variables.
只有在从托管到本地类型转换并且你所转换的本地类型没有自动删除的析构函数时需要context,marshaling context在它的析构函数中释放掉申请的本地类型。因此,需要context的转换仅仅在context删除之前有效,如果想保存marshled的值,必须把他存在自己重新声明的变量中。
由上可知:
1、托管到本地类型转换需要context,本地类型没有析构函数,因为要负责回收空间
2、对于原生类型转托管类型不需要context
3、在需要context的转换中,转换后的变量要保存到自己重新开辟的空间,否则在context析构时会回收内存
还需要注意一点(摘自MSDN)
If you have embedded NULL s in your string, the result of marshaling the string is not guaranteed. The embedded NULL s can cause the string to be truncated or they might be preserved.