我正在使用LoadLibrary
显式加载DLL并使用GetProcAddress
从中加载函数。到现在为止还挺好。 DLL的头文件(readline.h)中定义了以下变量:
READLINE_DLL_IMPEXP FILE *rl_outstream;
此变量由DLL内部使用,这就是为什么我必须在DLL内部更改它"#34;。我是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?
答案 0 :(得分:2)
如果需要在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
>