为啥传统的 GetProcAddress 到 std::function 工作不简单

Posted

技术标签:

【中文标题】为啥传统的 GetProcAddress 到 std::function 工作不简单【英文标题】:Why traditional GetProcAddress to std::function is not working straightforward为什么传统的 GetProcAddress 到 std::function 工作不简单 【发布时间】:2019-04-17 21:17:28 【问题描述】:

如标题所示,我想将 GetProcAddress 转换为 std::function。是的,堆栈溢出有多种解决方案,但没有一个能真正解释为什么需要这些解决方法。我无法真正理解确切的错误信息以及它发生的原因。示例源码很简单:

#include <functional>
#include <Windows.h>

using fn_NtAllocateVirtualMemory = NTSTATUS (NTAPI*)(
        HANDLE      ProcessHandle,
        PVOID*      BaseAddress,
        ULONG_PTR   ZeroBits,
        PSIZE_T     RegionSize,
        ULONG       AllocationType,
        ULONG       Protect
    );

int main()

    std::function<fn_NtAllocateVirtualMemory> myFn(reinterpret_cast<fn_NtAllocateVirtualMemory>(0xDEADBABE));

(https://godbolt.org/z/FhaeLA)

那么,我的问题是为什么会出错?


相关: 我也试过这个: Function pointer to multiple argument C++11 std::function: Templating GetProcAddress 但是也编译失败(https://godbolt.org/z/1wSDZj)

我还发现了这个话题: C++ Dynamically load arbitrary function from DLL into std::function 这可能会起作用(我还没有尝试过,我很快就会这样做)但我试图理解为什么这种看起来神秘的巨大样板是必要的。


注意事项:

显然 0xDEADBEEF 将被替换为必要的地址。 我正在使用 Visual Studio 2019 进行编译,但显然欢迎任何通用答案

【问题讨论】:

【参考方案1】:

std::function 将签名作为模板参数,而不是指针。

应该是这样的:

using fn_NtAllocateVirtualMemory = NTSTATUS NTAPI (
        HANDLE      ProcessHandle,
        PVOID*      BaseAddress,
        ULONG_PTR   ZeroBits,
        PSIZE_T     RegionSize,
        ULONG       AllocationType,
        ULONG       Protect
    );

int main()

    std::function<fn_NtAllocateVirtualMemory> myFn(
        reinterpret_cast<fn_NtAllocateVirtualMemory*>(0xDEADBABE));

【讨论】:

啊,我明白了。请注意,您应该更改 NTAPI 和 NTSTATUS 的顺序,因为这样会失败。否则,这很酷:) @original.roland:订单已更改。

以上是关于为啥传统的 GetProcAddress 到 std::function 工作不简单的主要内容,如果未能解决你的问题,请参考以下文章

LoadLibraryA与GetProcAddress介绍

GetProcAddress与__declspec(dllimport)

动态载入DLL所需要的三个函数详解(LoadLibrary,GetProcAddress,FreeLibrary)

动态载入DLL所需要的三个函数详解(LoadLibrary,GetProcAddress,FreeLibrary)

GetProcAddress() 为 .NET DLL 返回 Nil

用stvp联机st-link烧写程序到stm8上为啥程序就是运行不起来,配置位该怎么设,有人知道吗?