设置显式链接DLL的内部变量

Setting an internal variable of an explicitly linked DLL

本文关键字:内部 变量 DLL 链接 设置      更新时间:2023-10-16

我正在用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?
  1. 如何正确设置此DLL变量?
  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
>