调用DLL
_declspec(dllexport) int add(int a,int b)
{
return a+b;
}
//////////
HINSTANCE hInst;
hInst=LoadLibrary("danny.dll");
typedef int (*ADDPROC)(int a,int b);
ADDPROC Add=(ADDPROC)GetProcAddress(hInst,MAKEINTRESOURCE(1));
if(!Add)
{
MessageBox("获取函数地址失败!");
return;
}
CString str;
str.Format("5+3=%d",Add(5,3));
MessageBox(str);
1.模块定义
dannyboy.def文件:
LIBRARY mydllname
EXPORTS
SetPortDown @1
SetPortUp @3
FirstScan @4
BeginScan @5
SEGMENTS
MySec READ WRITE SHARED
dannyboy.cpp源文件:
#pragma data_seg("MySec")
int g=90;
#pragma data_seg()
#pragma comment(linker,"/section:MySec,RWS")
/*
BOOL WINAPI DllMain(
HINSTANCE hinstDLL, // handle to the DLL module
DWORD fdwReason, // reason for calling function
LPVOID lpvReserved // reserved
)
{
return 1;
}*/
int SetPortDown(int a)
{
return g+a;
}
int SetPortUp(int a)
{
return g+a;
}
int FirstScan(void)
{
return 1;
}
void BeginScan(void)
{
AfxMessageBox("");
}
2.c语言
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
}
extern "C" __declspec(dllexport) int myadd(int a,int b);
myadd(int a,int b)
{
AfxMessageBox("1");
return a+b;
}
调用:
#include "windows.h"
#include "iostream.h"
typedef int (*fun)(int a);
int main(int argc, char* argv[])
{
HINSTANCE h=LoadLibrary("C:\\Program Files\\Microsoft Visual Studio\\MyProjects\\dannyboy\\Debug\\dannyboy.dll");
if(h==NULL)return 1;
fun add=(fun)GetProcAddress(h,"SetPortDown");
if(add!=NULL)cout<<add(3);
return 0;
}