• 用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 = '';

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

  • 相关阅读:
    CSS选择器
    认识CSS样式
    1003 Max Sum(动态规划)
    Python_oldboy_自动化运维之路(八)
    Python_oldboy_自动化运维之路_全栈考试(七)
    Python_oldboy_自动化运维之路_函数,装饰器,模块,包(六)
    ibm x3550m4 开启cpu高性能模式
    Python_oldboy_自动化运维之路_全栈考试(五)
    Python_oldboy_自动化运维之路(四)
    Python_oldboy_自动化运维之路(三)
  • 原文地址:https://www.cnblogs.com/TianFang/p/4946021.html
Copyright © 2020-2023  润新知