C++ 载入dll

来源:互联网 发布:网络广播方案 编辑:程序博客网 时间:2024/05/16 17:39

1.新建一个项目生成dll


首先我们新建一个项目生成一个Dynamic Library(动态链接库) dll


里面非常简单,只有一个add方法。等下我们就要在其他项目里尝试载入这个dll,调用里面的这个add方法。


// MyDLL.cpp : Defines the entry point for the DLL application.//#include "stdafx.h"extern "C"{ _declspec(dllexport) int add(int x, int y);}int add(int x, int y){    return x + y;}BOOL APIENTRY DllMain( HANDLE hModule,                        DWORD  ul_reason_for_call,                        LPVOID lpReserved ){    return TRUE;}

如果开始项目不是没有生成dll,记得打开项目的属性,选择Dynamic Library


2.新建一个项目载入dll


// DLLTest.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <windows.h>  //must include thistypedef int (*MyAdd)(int x, int y);int main(int argc, char* argv[]){HMODULE hmod = NULL;hmod = ::LoadLibrary("MyDLL.dll"); //load dllif(hmod == NULL){       printf("load MyDLL.dll failed!");       return 0;}MyAdd Add = (MyAdd)GetProcAddress(hmod, "add");if(!Add){       printf("get function failed!");       return 0;}printf("test add(): 1+2=%d\n", Add(1,2)); ::FreeLibrary(hmod); // release resourcegetchar();return 0;}

效果图:



成功调用!

项目下载地址:c++动态载入dll

文章源地址:http://www.waitingfy.com/?p=654


原创粉丝点击