c++ - 如何动态使用 GetProcAddress

标签 c++ c winapi visual-c++ dll

正如我们所知,我们可以使用 GetProcAddress 从 DLL 句柄获取函数指针,例如在 DLL 中定义的方法 foo:

int foo(long)

对于 foo 函数,我们可以得到这样的函数指针:

typedef int(* FOO_FUNC)(long)
FOO_FUNC pFooFunc = (FOO_FUNC) GetProcAddress(dllHandle, "foo")

但是我们正在考虑是否可以使它进一步动态化,比方说,我知道我有一个输入参数列表及其对当前方法正确的类型,我想在 dll 上调用此方法,然后获取输出参数列表(以及它们的类型)

//VARIANT would be able to hold different type of data with different type
std::vector<VARIANT> inputArguments;
std::string methodName = "foo"
void * pFunc = GetProcAddress(dllHandle, methodName.c_str())
std::vector<VARIANT> outputArguments;
callMethodDynamically(pFunc, inputArgument, &outputArguments)

是否可以在 C/C++ 中实现上述 callMethodDynamically?我能想到的唯一方法是我们必须将参数压入堆栈,然后调用 pFunc。我想那将是汇编语言。这里还有其他方法吗?我们也必须在这里处理不同的调用约定(stdcall、cdecl)。

最佳答案

为每个实函数编写一个包装函数。

例如

int addNumbers( int x, int y ) { return x + y; }

void addNumbersW( std::vector<VARIANT>& inArgs, std::vector<VARIANT>& outArgs )
{
    // decode in args somehow
    int x = getArg( inArgs, 0 );
    int y = getArg( inArgs, 1 );
    int r = addNumbers( x, y );
    addArg( outArgs, r );
}

您或许可以为每个函数原型(prototype)编写一系列包装函数,并使用一些宏来简化使用。

关于c++ - 如何动态使用 GetProcAddress,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10922375/

相关文章:

c++ - 如何捕获部分屏幕并将其保存为 BMP?

c++ - 如何将 WinAPI 应用程序封装到 C++ 类中

c++ - 编译检查是否编译为静态库

c - 为什么这个函数在第一次调用后不返回指针?

c - 32位环境下c中指针的大小

套接字服务器代码中的编译错误

windows - 我的 32 位应用程序可以做什么来消耗数 GB 的物理 RAM?

c++ - 与第 3 方库链接导致 openssl 中出现段错误

c++ - MOG 和 GMM 算法之间有区别吗?或者是一样的吗?

c++ - gsl_histogram_find 给出段错误(c++,gsl)