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

时间:2014-05-18 17:40:26

标签: c++ dll

我正在使用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?
  1. 如何正确设置此DLL变量?
  2. 我应该在哪里寻找解决问题的方法?

1 个答案:

答案 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
>