這段時間用到了dll的調用,這里總結下,也方便我以后使用。
一、生成dll(基於VS2010)
1、選擇“Win32 Console Application”,建立工程;
2、向導中的“Application type”選擇Dll,並在“Additional options”選項中勾選“Empty Project”;
3、點擊“Finish”完成向導;
4、添加文件CallTest1.cpp,添加如下代碼:
#include <windows.h> BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { return TRUE; } extern "C" _declspec(dllexport) int Max(int i1,int i2) { return (i1>i2)?i1:i2; }
5、編譯生成dll文件;
二、C++調用dll(基於VS2010)
1、選擇“Win32 Console Application”,建立工程;
2、向導中的“Application type”選擇“Console Application”,並在“Additional options”選項中勾選“Empty Project”;
3、點擊“Finish”完成向導;
4、添加文件dllCall.cpp,添加如下代碼:
//dll的顯式調用 #include <stdio.h> #include <windows.h> typedef int(*pMax)(int a,int b); void main(void) { HINSTANCE hDLL; pMax Max; hDLL=LoadLibrary("dllTest1.dll");//加載動態鏈接庫文件; Max=(pMax)GetProcAddress(hDLL,"Max"); int a=Max(5,8); printf("比較的結果為%d\n",a); FreeLibrary(hDLL);//卸載文件; getchar(); }
5、進入工程的屬性選項,選擇“Use Multi-Byte Character Set”;
6、編譯程序,將dllTest1.dll文件copy到和dllCall.exe同一目錄並運行;
三、c#調用dll(基於VS2010)
1、選擇“Console Application”,建立dllCallCS工程;
2、在Program.cs文件中添加如下代碼: using System.Runtime.InteropServices;
3、導入dll文件: [DllImport("dllTest1.dll")] public static extern int Max(int i1, int i2); 4、添加測試代碼:
int ret = Max(1, 2);
if (1 == ret)
Console.WriteLine("test");
else
Console.WriteLine("test2");
5、編譯程序,將dllTest1.dll文件copy到和dllCallCS.exe同一目錄並運行;
附Program.cs文件完整代碼:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; namespace dllCallCS { class Program { [DllImport("dllTest1.dll")] public static extern int Max(int i1, int i2); static void Main(string[] args) { int ret = Max(1, 2); if (1 == ret) Console.WriteLine("test"); else Console.WriteLine("test2"); } } }
四、Python調用dll(基於Python2.7)
1、建立文件dllCall3.py文件,填充如下代碼:
from ctypes import * dll = CDLL("dllTest1.dll") print dll.Max(1, 3)
2、將dllTest1.dll文件復制到該目錄,運行程序;
好,就這些了,希望對你有幫助。
本文github地址:
https://github.com/mike-zhang/mikeBlogEssays/blob/master/2013/20130107_dll開發及調用.md
歡迎補充