用C++/CLI搭建C++和C#之间的桥梁(三)—— 基本类型

数值类型

对于基本的数值类型,在C++/CLI中是可以直接映射为托管类型的数值的,可以同时应用于托管类型和非托管类型,编译器会将其自动转换。

基本类型

System命名空间中对应的类

注释/用法

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::Stringchar*,系统没有直接的语法支持。方法有很多种,我通常使用如下方式来转换:

    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文章扩扩展封送处理库,这里就不多介绍了。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值