一個簡單的調用動態庫的實例


先創建一個動態庫dll工程

工程中添加 dlltest.cpp  dlltest.def  dlltest.h

dlltest.h

//dlltest.h
extern __declspec(dllexport) int FuncTest();

dlltest.cpp

//dlltest.cpp
__declspec(dllexport) int FuncTest(int a )
{
	if (a = 1)
	{
		return 100;
	}
}

dlltest.def

LIBRARY	"testmydll"
EXPORTS
	FuncTest

 

 

編譯後生成dlltest.dll  dlltest.lib

再新建一個Win32控制檯工程用來調用dlltest.dll  

將dlltest.dll拷貝到Win32的Debug目錄下面

Win32項目中dll.cpp文件如下

#include <iostream>   
#include "string"   
#include <stdio.h>  
#include <windows.h>
using namespace std;

int main()
{
	typedef int (*HFUNC)(int a );
	HINSTANCE hDLL = LoadLibrary("testmydll.dll");
	if (hDLL)
	{
		HFUNC hFun = (HFUNC)GetProcAddress(hDLL,"FuncTest");
		if (hFun)
		{
			int a =1;
			int b = hFun(a);
			printf("%d\n",b);
		}
	}

}


 

編譯執行則調用了dlltest.dll 打印出100

 

 

 

如果是調用 dlltest.lib的話,就要將dlltest.lib拷貝到工程目錄下(Debug上一級),編譯的時候就直接鏈接了,另外還要把頭文件 dlltest.h加到工程中

Win32項目中dll.cpp中的代碼如下

#include <iostream>   
#include "string"   
#include <stdio.h>  
#include <windows.h>
#include "dlltest.h"
using namespace std;
#pragma comment(lib,"testmydll.lib")
__declspec(dllimport) int FuncTest(int a );
int main()
{
	int b = FuncTest(1);
	printf("%d\n",b);
	return 0;
}


編譯執行打印出100

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章