C++/CLI入门概要

什么是C++/CLI

C++/CLI的链接

上图实现cli编译的obj文件和非cli编译的目标文件之间实现链接。

上图实现cli编译的obj文件和lib文件之间进行链接

上图实现cli编译的代码对非cli编译的dll的引用

C++/CLI基本语法

  • 基本类型

从上表中可以发现,在C#里面不同命令空间,或类成员的方位使用的是.,在CLI中使用的是::

  • 托管内存

托管内存受到垃圾收集器进行释放管理。托管堆内存的申请使用关键字gcnew,如:System::String^ name = gcnew System::String(L'a', 10),此处需要注意的是非托管类型不能使用gcnew来申请托管内存。在纯粹的c++中,指针对象是使用星号*标识,此处gcnew的到的对象是用^进行标识的。同时关键字nullptr也能够直接赋值给nameSystem::String^ name=nullptr;

  • System::String

System::String的操作与c#中String的操作基本保持一致。

String^ str = string::Empty;
str1 += "a";
str1 = str1 + "a";
str1 = String::Concat(str1, "a");
String^ str2 = str1->ToUpper();
  • Managed Arrays

二维数组的定义如下:

array<int,2>^ arr = gcnew array<int,2>(2,2);
arr[0,0] = 1; arr[0,1] = 2;
arr[1,0] = 3; arr[1,1] = 4;

// managed type的对象数组
// array<System::String> a; 这种实现方式是非法的,应该为
array<System::String^> a;
  • Stream-Based IO

// Read bytes from file
FileStream^ fs = gcnew FileStream("SampleFile.txt", FileMode::Open);
int bytesInFile = fs->Length;
array<Byte>^ bytes = gcnew array<Byte>(bytesInFile);
fs->Read(bytes, 0, bytesInFile);
String^ textInFile = Encoding::ASCII->GetString(bytes);
  • Managed Exception Handling

StreamReader^ sr = gcnew StreamReader(arg);
try
{
    TextWriter^ tw = Console::Out;
    tw->WriteLine("File {0}", arg);
    DumpTextReader(sr, tw);
}
catch (Exception^ exc)
{
    // Do something
    throw;
}
finally
{
    sr->Close();
}
  • Casting Managed Types
WebRequest^ req = GetWebRequestFromSomWhere();
if (dynamic_cast<FtpWebRequest^>(req) != nullptr)
{
    ;
}
  • 自定义common type system(CTS)类型

// 此处使用ref class替代class
ref class ManagedReferenceType
{
    int aPrivateField;
public:
    void APublicFunction();
};

// 定义一个value type
public value class Point
{
    int x;
    int y;
public:
    Point(int x, int y);
};

gcnew array<V>(100); // V: value type
gcnew array<R^>(100); // R: ref type
  • initonly

这个关键字和c#中的readonly的含义是相同的。

ref class MathConstants
{
public:
    static initonly double Pi = 3.1415926; // 直接初始化
}

VS中创建C++/CLI项目

  • 新建项目

  • 常见项目属性设置
    • Configuration Platform:选择平台,win32或者是x64
    • General - 自定义输出目录
    • C/C++ General: 设定额外的头文件目录
    • Linker General:设定额外的lib库目录
    • Linker Input:设置依赖的lib库
  • 17
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Rains卍Soft

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值