如何在C++Builder创建混合DLL?RAD Studio10+加载C#托管DLL求助
在C++Builder中创建混合DLL及C#托管DLL加载方案
问题1:C++Builder创建混合DLL
混合DLL指同时包含原生C代码与托管.NET代码的动态链接库,在RAD Studio中可通过C/CLI实现:
新建C++/CLI DLL项目
打开RAD Studio,依次选择File > New > Other > C++Builder > CLR > CLR Dynamic-Link Library,指定目标平台(Win32/Win64)与项目名称。编写原生C++逻辑
添加原生代码文件,导出供托管层调用的函数:// NativeUtils.h #pragma once extern "C" __declspec(dllexport) int NativeSum(int a, int b); // NativeUtils.cpp #include "NativeUtils.h" int NativeSum(int a, int b) { return a + b; }编写托管C++/CLI包装层
创建托管类封装原生函数,让.NET代码可直接调用:// ManagedWrapper.h #pragma once #include "NativeUtils.h" using namespace System; namespace MixedDLL { public ref class NativeMath { public: static int Sum(int a, int b) { return NativeSum(a, b); } }; }编译生成
选择匹配的.NET Framework版本(RAD Studio 10+默认支持4.x系列),编译后即可得到混合DLL。
问题2:RAD Studio 10+中C++/CLI DLL加载C#托管DLL
替代COM互操作的方案是直接通过C++/CLI的.NET集成特性引用并调用C# DLL:
准备C#托管类库
使用Visual Studio创建C#类库,编写公开类型:namespace CSharpTools { public class StringHelper { public string ReverseString(string input) { char[] arr = input.ToCharArray(); Array.Reverse(arr); return new string(arr); } } }编译时确保目标.NET版本与C++/CLI项目一致。
在C++/CLI项目中引用C# DLL
右键C++/CLI项目,选择Add > Reference,浏览并添加编译好的C# DLL文件。调用C#代码
在C++/CLI代码中直接实例化C#类并调用方法:#include <vcclr.h> using namespace System; using namespace CSharpTools; extern "C" __declspec(dllexport) const char* CallCSharpReverse(const char* input) { StringHelper^ helper = gcnew StringHelper(); String^ result = helper->ReverseString(gcnew String(input)); return (const char*)(Marshal::StringToHGlobalAnsi(result)).ToPointer(); }社区实践要点(来自Stack Exchange讨论)
- 必须保证C++/CLI项目与C# DLL的目标平台一致(同x86或x64),否则会出现加载失败
- 原生代码中持有托管对象时,使用
gcroot<T>类型避免对象被GC回收 - 若存在版本冲突,可通过添加
app.config文件配置程序集绑定重定向 - 该方案无需注册COM组件,避免了COM互操作的版本兼容性问题
内容的提问来源于stack exchange,提问作者MathewJoy
相关产品推荐
相关产品推荐

