1、dll導出程式部分代碼
.def檔案定義
LIBRARY "TestDll"
EXPORTS
;
fnTestDll @1
Add @2
代碼.h
typedef int(WINAPI *CallBackFn)(int n); //回調函數
// 這是導出函數的一個示例。
int WINAPI fnTestDll(CallBackFn pfn);
int WINAPI Add(int, int); // 這裡去掉__cdecl是等同的
代碼.cpp
#include "stdafx.h"
#include "TestDll.h"
int WINAPI fnTestDll(CallBackFn pfn)
{
return pfn(50);
}
int WINAPI Add(int a, int b)
{
return a+b;
}
//dll生成名字為testdll.dll
2、測試程式
#include "stdafx.h"
#include<windows.h>
#include<iostream>
typedef int(__cdecl *CallBackFn)(int n); //錯誤
//typedef int(WINAPI *CallBackFn)(int n);//正确
/*
此示例示範當給函數傳遞回調的時候 (__cdecl 與__stdcall) 調用棧不比對 導緻的崩潰問題
(_CRT_DEBUGGER_HOOK(_CRT_DEBUGGER_GSFAILURE)
*/
int Fun(int n)
{
return n;
}
int _tmain(int argc, _TCHAR* argv[])
{
HMODULE h = LoadLibrary(L"testdll.dll");
if(h == NULL)
{
return -1;
}
typedef int(__cdecl *fnTestDll)(CallBackFn pfn);
//typedef int(WINAPI *fnTestDll)(CallBackFn pfn);//正确
fnTestDll pFn = NULL;
pFn = (fnTestDll)GetProcAddress(h,"fnTestDll");
if(pFn)
{
std::cout<<pFn(Fun)<<std::endl;
}
return 0;
}