一.静态&动态装载DLL
C++中接口通过编译为DLL对外提供调用,C#需要将DLL加载至本应用才可实现C++接口调用.
1.静态装载
C#应用程序在编译为可执行exe时将外部DLL装载至本应用中,例如在CSC编译指令中添加相关参数可实现DLL引用.
csc /reference:user32.dll /out:HelloWorld.exe
2.动态装载
C#应用程序在运行时通过调用kernel32.dll中LoadLibrary完成外部DLL的装载.
二.编译C++DLL
实现C++方法MYFunction,将接口编译为MyClass.dll
// MyClass.h
#ifdef BUILD_DLL
#define MY export __declspec(dllexport)
#else
#define MY export __declspec(dllimport)
#endif
class MY MyClass {
public:
void MYFunction();
};
// MyClass.cpp
#include "MyClass.h"
void MyClass::MYFunction() {
// Implementation
}
三.使用DllImport映射LoadLibrary接口
public static class Kernel32
{
[DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr LoadLibrary(string lpFileName);
}
四.使用DllImport映射MYFunction接口
static class Tools
{
[DllImport("MyClass.dll", SetLastError = true)]
internal static extern void MYFunction();
}
五.C#调用DLL中接口
public static void Main()
{
Kernel32.LoadLibrary("myclass.dll");
Tool.MYFunction();
}



















