用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文章擴擴展封送處理庫,這里就不多介紹了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM