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

标签 c++ dll

我使用 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
>

关于c++ - 设置显式链接 DLL 的内部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23724955/

相关文章:

c++ - 没有对 std::index_sequence 中的包扩展进行诊断

c++ - 线程池C++实现问题

.net - System.Reactive dll 丢失

.net - SQLite,将平台特定的 dll 复制到 bin 文件夹

c++ - 链接器如何在剥离的动态库中定位代码?

C++ MPI 标准 3

c++ - 根据属性从列表中选择元素

c++ - 友元函数声明为成员函数

c# - 以编程方式注册 C#/VB.NET COM dll

gcc - 想要很好地理解内存级别的共享库