在实际C#开发项目中,存在如下两种情况
- C#调用第三方库,而第三方库是使用C++编写的;
- 牵涉到项目源代码保密,C#代码容易被反编译,因此抽取核心算法部分使用C++编写
这时候就涉及C#托管代码与C++非托管代码互相调用。
本文介绍C#调用C++的方法以及在C#调用C++产生问题的排查过程和经验总结。
下面介绍C#如何静态和动态调用C++库;
一、C#中静态调用C++动态链接
1. 建立 CppDemo,建立的时候选择DLL动态库。
2. 在DllDemo.cpp文件中添加一个Add函数
extern "C" __declspec(dllexport) int Add(int a,int b)
{
return a+b;
}
3. 编译生成DllDem.dll提供C#使用.
4. 新建C#工程,选择控制台测试程序InteropDemo
5. 在Program.cs中添加引用:using System.Runtime.InteropServices;
6. 在pulic class Program添加如下代码:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace InteropDemo
{
class Program
{
[DllImport("CppDemo.dll", EntryPoint = &