C++调用C# (使用C++/CLI)
简介
C++/CLI简介见上文 C#调用C++ (使用C++/CLI) - 咸鱼翻身? - 博客园 (cnblogs.com)
新建解决方案->CPlusCSharpSolution
新建C#类库->CSharpNative
新建类NativeCalculate
1 public class NativeCalculate 2 { 3 public int Add(int a, int b) 4 { 5 return a + b; 6 } 7 }
新建CLI类库(DLL)->CSharpWrapper
添加CSharpNative引用
添加NativeCSharpWrapper类
//NativeCSharpWrapper.h #pragma once using namespace System; namespace CSharpWrapper { public ref class NativeCSharpWrapper { public: static int Add(int a, int b); }; }
//NativeCSharpWrapper.cpp #include "pch.h" #include "NativeCSharpWrapper.h" using namespace CSharpWrapper; using namespace CSharpNative; int NativeCSharpWrapper::Add(int a, int b) { int sum = 0; NativeCalculate^ nativeCalculate = gcnew NativeCalculate(); // 创建C#类的实例 sum = nativeCalculate->Add(a, b); // 调用C#方法 return sum; }
创建非托管类NativeCSharpWrapper
创建非托管类调用NativeCSharpWrapper 并提供对外导出
//NativeCalculate.h #pragma once #ifndef NATIVE_CLASS_H #define NATIVE_CLASS_H class __declspec(dllexport) CPlusCalculate { public: static int Add(int a, int b); }; #endif // NATIVE_CLASS_H
// NativeCSharpWrapper.cpp #include "pch.h" #include "NativeCSharpWrapper.h" using namespace CSharpWrapper; using namespace CSharpNative; int NativeCSharpWrapper::Add(int a, int b) { int sum = 0; NativeCalculate^ nativeCalculate = gcnew NativeCalculate(); // 创建C#类的实例 sum = nativeCalculate->Add(a, b); // 调用C#方法 return sum; }
新建C++控制台项目->CPlusConsoleApplication
添加包含目录 CSharpWrapper.h
添加CSharpWrapper.lib附加库目录
添加附加库依赖项CSharpWrapper.lib
main函数调用
main函数调用C++/CLI项目CSharpWrapper进而调用CSharpNative
#include <iostream> #include "CPlusCalculate.h" int main() { int sum = CPlusCalculate::Add(50, 40); }
天行健,君子以自强不息;
地势坤,君子以厚德载物;