C#与C++ DLL的互操作
C#调用C++ DLL要点:
1.C++自己编写的函数必须为导出函数.
2.为把C++函数编译为导出函数,在函数前面加上
extern "C" __declspec(dllexport)
extern "C":按C语言的进行编译
__declspec(dllexport):表示导出函数,另外导入函数为__declspec(dllimport)
C++项目属性:
无公共语言运行时支持
C/C++ => 高级:
1.编译为 => 编译为 C++ 代码 (/TP)
2.调用约定=>__stdcall (/Gz) 注意:调用约定必须是 stdcall、cdecl 或 thiscall 之一。
C++函数:
#include "stdafx.h" #include "stdio.h" extern "C" __declspec(dllexport) void PrintMsg(const char* msg) { printf("我在C++里编写:PrintMsg.\n下面的字符串是C#传入的:%s\n", msg); return; }
C#调用:
static void Main(string[] args) { PrintMsg(@"C#夜未眠"); Console.ReadKey(); } #region 自定义DLL互操作: [DllImport(@"E:\code\ConsoleApplication3\Debug\ConsoleApplication3.dll", CallingConvention = CallingConvention.StdCall)] static extern void PrintMsg(string msg); #endregion
运行结果:
另外附加一个:
SayStdC();//这个函数在vs里点启动显示不出来,要进入exe文件目录点击exe执行才能看到
//直接对标准微软C运行库中的函数进行平台调用 [DllImport("user32.dll", EntryPoint = "MessageBox")] public static extern int MessageBox(int hwnd, string lpText, string lpCaption, int wType); [DllImport("msvcrt.dll",CallingConvention = CallingConvention.Cdecl)] static extern int puts(string msg);//puts函数将字符串传送到输入流中 [DllImport("msvcrt.dll",CallingConvention = CallingConvention.Cdecl)] static extern int _flushall();//手动清除所有输入流 public static void SayStdC() { puts("puts函数调用"); _flushall(); } public static void SayWinAPI() { MessageBox(0, "Hello C# Code!", "CSharp互操作", 0); }
运行效果: