C++中CLI模块的基本类型有哪些

发布时间:2022-07-04 13:44:22 作者:iii
来源:亿速云 阅读:133

本文小编为大家详细介绍“C++中CLI模块的基本类型有哪些”,内容详细,步骤清晰,细节处理妥当,希望这篇“C++中CLI模块的基本类型有哪些”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

数值类型

对于基本的数值类型,在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::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++中CLI模块的基本类型有哪些”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. C++的内置基本类型和初始化
  2. C++中变量和基本类型的示例分析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++ cli

上一篇:JS如何实现添加缓动画

下一篇:vue.js基于ElementUI如何封装CRUD的弹框组件

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》