DLL函数调用以及回调函数设置

来源:互联网 发布:sql语句where条件查询 编辑:程序博客网 时间:2024/04/26 01:54
window开发中,需要将一些库编译成DLL以共享给其他程序使用,那么怎样调用DLL函数

1.只是普通调用DLL中的函数

1.1在VS2012中创建一个DLL程序,MyDLL

新建一个MyDLL.h头文件,加入如下代码:

extern "C" _declspec(dllexport) void test();

在源文件中,添加如下代码:

#include "MyDLL.h"#include <stdio.h>void test(){    printf(“hello, test”);}

编译成DLL,记下DLL的路径。

 

1.2创建另一个应用程序win32 console application工程UseDLL

在包含main的文件中,例如UseDLL.cpp中添加如下代码,注意DLL的路径要填写你刚才生成的DLL路径:

#include "stdafx.h"#include <Windows.h> typedefvoid (*Test)();int main(){    HMODULE p =LoadLibrary(L"C:/Users/rspxri/Documents/VisualStudio 2012/Projects/MyDLL/x64/Debug/MyDLL.dll");    Test mytest = (Test)GetProcAddress(p,"test");    mytest();    return 0;}

 2.设置回调函数

当exe程序调用DLL时,给DLL中设置回调函数,这样,DLL可以调用exe中的函数,如下图

修改以上工程代码:

2.1MyDLL

以下是MyDLL的头文件

MyDLL.htypedef void (*CallbackFun)(const char* input); extern "C" _declspec(dllexport) void SetCallBackFun(CallbackFun callbackfun);extern "C" _declspec(dllexport) void test();


以下是DLL源文件

MyDLL.cpp#include "MyDLL.h"CallbackFun myCallback = NULL;void SetCallBackFun(CallbackFun callbackfun){    myCallback = callbackfun;}void test(){    myCallback("in the test function");}

2.2UseDLL

#include "stdafx.h"#include <Windows.h>typedef void (*CallbackFun)(const char* input); typedef void (*SetCallBackFun)(CallbackFun callbackfun); typedef void (*Test)();void myfunction(const char* input){    printf(input);}int main(){    HMODULE p =LoadLibrary(L"C:/Users/rspxri/Documents/VisualStudio 2012/Projects/MyDLL/x64/Debug/MyDLL.dll");    SetCallBackFun setcallbackfun = (SetCallBackFun)GetProcAddress(p,"SetCallBackFun");        Test mytest = (Test)GetProcAddress(p,"test");    setcallbackfun(myfunction);         mytest();    return 0;}

 

2 0
原创粉丝点击