日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C++超集C++/CLI模塊的基本類型_C 語言

作者:天方 ? 更新時間: 2022-08-26 編程語言

數值類型

對于基本的數值類型,在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++ 互操作封送 ANSI 字符串

結構體

除了基本類型外,有時我們也需要對結構體進行映射,MS也提供了相應的映射函數,非常方便。具體可參考MSDN文章擴擴展封送處理庫,這里就不多介紹了。

原文鏈接:https://www.cnblogs.com/TianFang/p/4946021.html

欄目分類
最近更新