摘要
需要三个项目
- c++代码 CPPProject
- c++包装器 CPPWrap
- c#包装器 CSharpWrap
CPPWrap
创建c++动态链接库项目
配置属性 - 高级 - C+/CLI属性 ,依次设置公共语言运行时支持、.NET目标框架(设置为需要的.net环境对应的版本即可)
调整公共语言运行时
调整项目属性 - C/C++ - 语言 - 符合模式调整为否
随后需要依次将对应的c++类做一层包装,将c++类中的公共属性通过包装器暴露出去即可
例:
//注意需要ref
public ref class AgentWrap
{
public:
//模拟代码,可以改成c++项目中的类型
Agent *agent;
std::vector<DetectedSheepRow> get_DetectedSheep();
void UpdateDetectedSheepLocation(int i, int timestep, Vector2f location);
void add_DetectedSheep(DetectedSheepRow newRow);
};
CSharpWrap
直接引用对应的CPPWrap,便可以直接在c#代码中使用c++对应的类型了
引用c#类型
c++中可以通过引入.net对应的名称空间来使用.net中的类型
// 通过命名空间引入.NET类型
using namespace System;
using namespace System::Collections::Generic;
// .NET动态数组
List<Double>^ datas = gcnew List<Double>();
datas->Add(0.1);
datas->Add(0.2);
datas->Add(0.3);
datas->Add(0.4);
datas->Add(0.5);
[参考]
123最佳实践
留待后查,同时方便他人