对于基本的数值类型,在C++/CLI中是可以直接映射为托管类型的数值的,可以同时应用于托管类型和非托管类型,编译器会将其自动转换。
bool | System::Boolean | bool dirty = false; |
char | System::SByte | char sp = ' '; |
signed char | System::SByte | signed char ch = -1; |
unsigned char | System::Byte | unsigned char ch = '\0'; |
wchar_t | System::Char | wchar_t wch = ch; |
short | System::Int16 | short s = ch; |
unsigned short | System::UInt16 | unsigned short s = 0xffff; |
int | System::Int32 | int ival = s; |
unsigned int | System::UInt32 | unsigned int ui = 0xffffffff; |
long | System::Int32 | long lval = ival; |
unsigned long | System::UInt32 | unsigned long ul = ui; |
long long | System::Int64 | long long etime = ui; |
unsigned long long | System::UInt64 | unsigned long long mtime = etime; |
float | System::Single | float f = 3.14f; |
double | System::Double | double d = 3.14159; |
long double | System::Double | long double d = 3.14159L; |
字符串CLI已经内置了:System::String,但C++的常用字符串有char*、wchar_t*、std::string等好多种,编译器提供了char*、wchar_t*到System::String的自动转换:
System::String^ s = "hello worold";
System::String^ s2 = L"hello worold";
另外,也可以使用gcnew创建托管字符串:
System::String^ s = gcnew String("hello worold");
但是,对于System::String转char*,系统没有直接的语法支持。方法有很多种,我通常使用如下方式来转换:
IntPtr ip = Marshal::StringToHGlobalAnsi(str);
const char* ch = static_cast<const char*>(ip.ToPointer());
//do something with ch
Marshal::FreeHGlobal(ip);
这里有个需要注意的地方是在使用完转换出来的const char*后需要释放掉转换过程中的Intptr,如果没有太多需要考虑性能的地方,大可以使用一个std::string将其拷贝走,写成如下函数形式:
#include <string>
using namespace std;
using namespace System;
using namespace System::Runtime::InteropServices;
string cast_to_string(String^ str)
{
IntPtr ip = Marshal::StringToHGlobalAnsi(str);
const char* ch = static_cast<const char*>(ip.ToPointer());
string stdStr = ch;
Marshal::FreeHGlobal(ip);
return stdStr;
}
参考文章:如何:使用 C++ 互操作封送 ANSI 字符串
结构体除了基本类型外,有时我们也需要对结构体进行映射,MS也提供了相应的映射函数,非常方便。具体可参考MSDN文章扩扩展封送处理库,这里就不多介绍了。