我使用 LoadLibrary
显式加载 DLL,并使用 GetProcAddress
从中加载函数。到目前为止,一切都很好。 DLL 的头文件(readline.h)中定义了以下变量:
READLINE_DLL_IMPEXP FILE *rl_outstream;
该变量由 DLL 内部使用,这就是为什么我必须“在 DLL 内部”更改它。我是 C++ 新手,找不到在我的父 cpp 文件中设置此变量的方法。这是我尝试过的:
hDLL = LoadLibrary("readline.dll");
hDLL.rl_outstream = fopen("outstream.txt","w");
这只会产生以下错误:
error C2228: left of '.rl_outstream' must have class/struct/union
type is 'HINSTANCE'
did you intend to use '->' instead?
- 如何正确设置此 DLL 变量?
- 我应该在哪里搜索才能找到问题的解决方案?
最佳答案
如果需要在DLL内部设置变量。您需要导出该变量。考虑以下示例:
我们有这个 DLL:
#include <cstdio>
#include <cassert>
#ifdef __cplusplus
extern "C"
{
#endif
FILE *rl_outstream;
void
do_something()
{
assert(rl_outstream);
fputs("HELLO", rl_outstream);
}
#ifdef __cplusplus
};
#endif
如果有一个名为rl_outstream
的导出变量,您可以像这样设置它的值:
#include <windows.h>
#include <cstdio>
#include <cassert>
int
main(int argc, char **argv)
{
FILE **rl_outstream;
void (*do_something)(void);
HMODULE hModule;
hModule = LoadLibraryW(L"./lib.dll");
assert(hModule);
rl_outstream = (FILE **) GetProcAddress(hModule, "rl_outstream");
assert(rl_outstream);
do_something = (void(*)(void)) GetProcAddress(hModule, "do_something");
assert(do_something);
*rl_outstream = fopen("out.txt", "w");
do_something();
fclose(*rl_outstream);
FreeLibrary(hModule);
return 0;
}
编译并执行test.exe
后:
>g++ -Wall lib.cpp -shared -o lib.dll
>g++ -Wall test.cpp -o test.exe
>test.exe
>type out.txt
HELLO
>
关于c++ - 设置显式链接 DLL 的内部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23724955/