在C++/CLI中必须用ref class/ref struct声明托管类型,成员需用^声明(如String^),原生类型不可直接嵌套,须用gcroot包装;引用.NET程序集用#using而非#include;/clr是唯一支持的编译模式。
必须用 ref class 或 ref struct 显式标记托管类型,原生 C++ 的 class 无法直接持有 System::String^ 或调用 System::Collections::Generic::List。编译器会拒绝混合使用(比如在原生类里放 String^ 成员),除非启用 /clr 编译选项且该类本身是托管的。
常见错误现象:error C3699: '^' : cannot use this indirection on type 'std::string' —— 这说明你试图对原生类型用句柄符号 ^;反过来,error C3673: 'MyNativeClass' : cannot be used as a managed type 则表明你把它当托管对象传给了 .NET API。
ref class)必须用 ^ 声明,如 System::String^ s = "hello";
ptr 或 gcroot 包装(见下节)#using "System.dll" 或项目属性中添加引用,不是 #include
不能直接把原生类实例作为托管类的数据成员(编译报错:C4368)。正确做法是用 gcroot 包装指针,或手动管理生命周期(new/delete)+ 在析构函数和终结器中释放。
典型场景:封装一个原生图像处理库(如 OpenCV cv::Mat),同时提供 .NET 接口供 C# 调用。
ref class ImageWrapper {
private:
gcroot _nativeMat;
public:
ImageWrapper() { _nativeMat = new cv::Mat(); }
~ImageWrapper() { this->!ImageWrapper(); }
!ImageWrapper() { delete _nativeMat; _nativeMat = nullptr; }
void Load(const System::String^ path) {
pin_ptr p = PtrToStringChars(path);
std::wstring wstr(p);
_nativeMat->imread(wstr, cv::IMREAD_COLOR);
}
}; 注意:gcroot 是 提供的模板,它让 GC 知道这个指针不参与托管内存回收,但能随托管对象一起被跟踪;pin_ptr 用于临时固定字符串内存,防止 GC 移动导致原生代码读到野指针。
原生代码默认看不到托管符号。必须通过“过渡层”——即一个带 __declspec(d 的托管 DLL 导出 C 风格函数,或用
llexport)static_cast 将托管回调转为函数指针(有限制)。
更可靠的做法是导出一个纯 C 接口,内部用 gcnew 创建托管对象并调用:
extern "C" __declspec(dllexport) int __cdecl ProcessImage(
const wchar_t* inputPath,
const wchar_t* outputPath)
{
try {
System::String^ in = gcnew System::String(inputPath);
System::String^ out = gcnew System::String(outputPath);
MyManagedProcessor::Process(in, out); // 托管静态方法
return 0;
} catch (...) { return -1; }
}关键点:
extern "C" + __declspec(dllexport),避免 C++ 名字修饰String^ 或任何托管类型给原生调用方SetLastError 传递错误Marshal::GetDelegateForFunctionPointer 转成 delegate(仅限 x86/x64 兼容模式)Visual Studio 2015 起,/clr:pure 和 /clr:safe 不再生成可验证 IL,且无法调用现代 .NET Core/.NET 5+ API。目前唯一支持的模式是 /clr(也叫“混合模式”),它生成本机机器码 + IL 混合模块,允许任意原生/托管互操作,但输出仍是 Windows-only PE 文件。
容易被忽略的地方:
/clr 编译的项目不能引用 .NET Standard 或 .NET 5+ 类库(只能引用 .NET Framework 4.x 或 .NET Core 3.1 的“桌面兼容”版本)Microsoft.VCxx.CRT.manifest 和 .NET Framework 运行时