码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-11-07 21:45:42      阅读:380      评论:0      收藏:0      [点我收藏+]

标签:

数值类型

对于基本的数值类型,在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 字符串

 

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

标签:

原文地址:http://www.cnblogs.com/TianFang/p/4946021.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!