看板 MaRoon
作者 標題 C++ DLL 製作 & 使用C++呼叫方式
時間 2015年01月28日 Wed. AM 02:57:19
環境:Dev-C++ 5.7.1
Compiler Options:TDM-GCC 4.8.1 64-bit Release
MinGW\lib
MinGW\bin
DLL_Project:裡頭兩個檔案分別是 dll.h 和 dllmain.cpp
使用DLL:run_dll.cpp
Compile → dllmain.cpp 產生 .dll 檔
→ run_dll.cpp 產生 .exe 檔
執行 run_dll.exe 顯示 The result is 30.000000 (呼叫.dll內的函式成功)
dll.h 程式碼:
#ifndef _DLL_H_
#define _DLL_H_
#if BUILDING_DLL
#define DLLIMPORT __declspec(dllexport)
#else
#define DLLIMPORT __declspec(dllimport)
#endif
extern "C"
{
__declspec(dllexport) double AddNumbers(double a, double b);
}
#endif
dllmain.cpp 程式碼:
/* Replace "dll.h" with the name of your header */
#include "dll.h"
#include <windows.h>
#include <iostream>
__declspec(dllexport) double AddNumbers(double a, double b){
return a+b;
}
run_dll.cpp 程式碼:
#include "dll.h"
#include <windows.h>
#include <cstdio>
// DLL function signature
typedef double (*importFunction)(double, double);
int main() {
importFunction addNumbers;
double result;
// Load DLL file
HINSTANCE hinstLib = LoadLibrary(".\\hi.dll");
if (hinstLib == NULL) {
printf("ERROR: unable to load DLL\n");
system("pause");
return 1;
}
// Get function pointer
addNumbers = (importFunction)GetProcAddress(hinstLib, "AddNumbers");
if (addNumbers == NULL) {
printf("ERROR: unable to find DLL function\n");
FreeLibrary(hinstLib);
system("pause");
return 1;
}
result = addNumbers(10, 20);
printf("The result is %f\n", result);
// Unload DLL file
FreeLibrary(hinstLib);
system("pause");
return 0;
}
--
※ 作者: KTR150Fi 時間: 2015-01-28 02:57:19
※ 看板: MaRoon 文章推薦值: 0 目前人氣: 0 累積人氣: 1477
回列表(←)
分享