c++生成、加载函数类型的动态库

21 篇文章 0 订阅

一、生成函数类型的动态库

1、创建一个动态库的工程

2、创建一个CPP文件名为:ExecCmd.cpp

内容如下:

#include <windows.h>

extern "C" {__declspec(dllexport) int _stdcall ExecCmd(char* pCmd,int nShow); }

int _stdcall ExecCmd(char* pCmd,int nShow)
{
    return WinExec(pCmd, nShow);
}

二、加载调用函数类型的动态库

1、创建一个Exe工程

2、创建一个CPP文件名为:main.cpp

内容如下:

#include <windows.h>
#include <iostream>
using namespace std;

int main(int argc, char* argv[])
{
    if (argc <=1)
    {
        return -1;
    }

    HINSTANCE hInst;
    hInst = LoadLibrary(L"ExecCmd.dll");
    if (hInst == INVALID_HANDLE_VALUE)
    {
        cout << "加载动态库失败。" << endl;
        return -1;
    }
    typedef int(_stdcall *ExecCmdProc)(char*,int);
    do 
    {
        ExecCmdProc ExecCmd = (ExecCmdProc)GetProcAddress(hInst, (LPCSTR)MAKEINTRESOURCE(1));
        if (ExecCmd == NULL)
        {
            cout << "获取函数地址失败" << endl;

            break;
        }
        ExecCmd(argv[1],1);
    } while (0);

    FreeLibrary(hInst);

    return 0;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
C++ 中,可以使用 Boost 库的 `boost::dll` 模块来实现动态加载和卸载代码,从而实现更灵活的程序设计和扩展功能。以下是加载动态库的基本步骤: 1. 使用 `boost::dll::shared_library` 加载动态库,该的构造函数接受动态库路径和加载选项(如 `boost::dll::load_mode::append_decorations`)。 ```c++ #include <boost/dll.hpp> boost::dll::shared_library lib("MyDll.dll", boost::dll::load_mode::append_decorations); ``` 2. 如果加载成功,可以使用 `lib.get<int(int, int)>("Add")` 函数获取动态库中导出函数的地址,该函数的模板参数为函数类型,参数为函数名。 ```c++ #include <boost/dll.hpp> typedef int (*PFunc)(int, int); // 定义函数指针类型 PFunc pAdd = (PFunc)lib.get<int(int, int)>("Add"); // 获取函数地址 ``` 3. 调用导出函数。 ```c++ int result = pAdd(1, 2); // 调用函数 ``` 4. 如果需要卸载动态库,可以使用 `lib.unload()` 函数释放动态库。 ```c++ lib.unload(); // 卸载动态库 ``` 需要注意的是,动态库中的函数必须使用 `BOOST_SYMBOL_EXPORT` 宏进行导出,例如: ```c++ #include <boost/config/export.hpp> BOOST_SYMBOL_EXPORT int Add(int a, int b) { return a + b; } ``` 同时,动态库需要使用 `-DBOOST_ALL_DYN_LINK` 宏进行编译,例如: ```sh g++ -shared -fPIC -o MyDll.dll MyDll.cpp -DBOOST_ALL_DYN_LINK ``` 其中,`-fPIC` 选项表示生成位置无关代码,以便在不同的进程空间中共享。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值