最近碰到有关C#调用MFC dll的问题,查了很多资料,参考了不少的网上博客,做了如下总结,C#动静态调用C++ dll,C++调用C#dll。也算一个简单的自我整理,有问题也请提出来,共同进步。
C# 静态调非托管C++ dll
1)C++ dll中含代码
extern "C" __declspec(dllexport) int Add(int a,int b)
{return a+b;}
2)C#调用dll dll放在C#生成的文件中 C#代码中
引用加上:using System.Runtime.InteropServices;
class Program
{
[DllImport("CppDemo.dll", EntryPoint = "Add", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)]
public static extern int Add(int a, int b); //DllImport请参照MSDN
static void Main(string[] args)
{
Console.WriteLine(Add(1, 2));
Console.Read();
}
}
DllImport参数说明
说明:
1、DllImport只能放置在方法声明上。
2、DllImport具有单个定位参数:指定包含被导入方法的 dll 名称的 dllName 参数。
3、DllImport具有五个命名参数:
a、CallingConvention 参数指示入口点的调用约定。如果未指定CallingConvention,则使用默认值CallingConvention.Winapi。Calling Convention是指程序在函数调用时传递参数和获取返回值所采用的方法:通过寄存器、或通过栈、或者是两者的混合。
注释:_stdcall 与_cdecl是两种不同的函数调用约定,区别在函数参数入栈的顺序,由调用函数还是被调用函数将参数弹出栈,以及产生函数修饰名的方法。对于参数可变的函数如