无法将全局变量从 dll 导入到应用程序中?

标签 c windows winapi dll global-variables

我有一个DLL

A.dll

这是啊

#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef __cplusplus
#define DLL_EXPORT extern "C" __declspec(dllexport) 
#else
#define DLL_EXPORT __declspec(dllexport)
#endif

DLL_EXPORT void function();
DLL_EXPORT char ** ReturnArr;

这是 A.c

void function()
{
char *str = "hello";
char *str1 = "how are you?";
ReturnArr = (char **)malloc(sizeof(char*) * 2);
for(;j<2;j++)
{
ReturnArr[j] = (char *) malloc(256);
if(NULL == ReturnArr[j])
break;
}
strcpy(ReturnArr[0],"str");
strcpy(ReturnArr[1],"str1");
}

现在我有使用 dll 的 Application.c

#include <windows.h>
#include <stdio.h> 

typedef int (__cdecl *MYPROC)(LPWSTR); 

_declspec(dllimport) char ** ReturnArr;

int main( void ) 
{ 
HINSTANCE hinstLib; 
MYPROC ProcAdd;
int a = 0;
BOOL fFreeResult, fRunTimeLinkSuccess = FALSE; 

// Get a handle to the DLL module.

hinstLib = LoadLibrary(TEXT("A.dll")); 

// If the handle is valid, try to get the function address.

if (hinstLib != NULL) 
{ 
ProcAdd = (MYPROC) GetProcAddress(hinstLib, "function"); 

// If the function address is valid, call the function.
if (NULL != ProcAdd) 
{
fRunTimeLinkSuccess = TRUE;
(ProcAdd) (L"Message sent to the DLL function\n"); 
printf("%s",Returnarr[0]);
}

fFreeResult = FreeLibrary(hinstLib); 
} 

// If unable to call the DLL function, use an alternative.
if (! fRunTimeLinkSuccess) 
printf("Message printed from executable\n"); 

return 0;

}

在 Visual studio CommonProperties->references:i 添加了 A.dll,它向我显示了编译器 ##error Error 1 error LNK2001: 无法解析的外部符号“__declspec(dllimport) char * ##* ReturnArr” (_imp?ReturnArr@@3PAPADA)”和“错误 2 fatal error LNK1120: 1 未解决 ##externals”

我如何实际导出全局变量并在我的应用程序中使用,请告诉我一种方法,如何在我的应用程序中实际打印 ReturnArr 作为全局变量

谢谢

最佳答案

如果您希望链接器解析 ReturnArr 导入变量,则必须将 A.LIB 添加到链接过程中。有多种方法可以做到这一点。

  1. 将 A.LIB 添加到“配置属性”->“链接器”->“输入”中的“附加依赖项”
  2. 在Application.c中添加#pragma comment(lib, "a.lib")
  3. 使 DLL 项目成为 EXE 项目和 EXE 项目的依赖项,并将配置属性 -> 链接器 -> 常规“链接库依赖项”设置为 yes。

旁注:

  1. 你确定要 strcpy(ReturnArr[0],"str"); ?可能 strcpy(ReturnArr[0],str); (没有 str 周围的引号)
  2. 如果静态链接到 A,则不需要 LoadLibrary 和 GetProcAddress。
  3. 您也可以只抑制 _declspec(dllimport) char ** ReturnArr;
  4. 您的 MYPROC 类型定义是错误的。 “function”的返回类型是void,而不是int
  5. 如果你想让EXE知道ReturnArr,只需将其设置为函数的返回值即可!

您应该尝试解释您到底想做什么

关于无法将全局变量从 dll 导入到应用程序中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19631290/

相关文章:

c - 如何修复 : OP-code isn't read out correctly

c - C99中bool类型可以返回什么?

c# - 无窗口任务栏按钮

windows - ClickOnce 和应用程序数据

CreateProcess 导致问题

c++ - win32 c++ 在没有子类化的编辑控件中检测到 'enter'?

c - 结构体数组中每个元素的 mpi 通信器

c - 文本隐写 C 程序的 GUI

c++ - 适用于 Windows 的 USB API

c++ - 没有子类化的 CAsyncSocket?