什么是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库