创建一个c++的DLL 项目 ,命名为learnDLL
在learnDLL.h 头文件上声明接口函数:
#pragma once
#ifndef LIB_H
#define LIB_H
extern "C" _declspec(dllexport) int add(int x, int y);
extern "C" _declspec(dllexport) int sub(int x, int y);
#endif
在learnDll.cpp 中写上接口函数的实现方法
#include "stdafx.h"
#include "learnDLL.h"
int add(int x, int y) {
return x + y;
}
int sub(int x, int y) {
return x - y;
}
运行生成项目
3.在c#中实现调用
创建一个c#项目,把上面生成的 learnDLL.dll 文件放到本项目的debug文件中
在c#中也创建一个类,专门用来管理这些接口
using System.Runtime.InteropServices;
namespace learn_cshape2
{
class Program
{
[DllImport("learnDLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int add(int x, int y);
static void Main(string[] args)
{
Console.WriteLine(add(10, 20).ToString());
Console.ReadKey();
}
}
}
这样定义之后在其他的C#程序中即可直接调用了。其中”CppDll.dll”是DLL文件名,保证在C#的输出目录下。声明的函数名称要么和CPP中的一致,要么不通过名字而通过EntryPoint = “#3”这种方式指定。确保编译器能找到接口
此种方法也可以实现类(C#中使用struct和IntPtr实现)的传输,但是需要在CSharp中重新编写类,并且变量的顺序、内存对齐方式可能都需要自己操心。尤其是我们类很多、类之间有嵌套等情况
MS网站有更详细的解释PInvoke和Marshal技术,可以根据这两个关键字在网络上好好查找下。
!!如何跟踪调试:在C#工程属性的Debug下面,check上Enable unmanaged code debugging即可。