C 无法将全局变量从dll导入应用程序?
我有一个动态链接库 动态链接库 这是A.hC 无法将全局变量从dll导入应用程序?,c,windows,winapi,dll,global-variables,C,Windows,Winapi,Dll,Global Variables,我有一个动态链接库 动态链接库 这是A.h #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) #end
#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;
#包括
#包括
#包括
#包括
#ifdef_uucplusplus
#定义DLL\u导出外部“C”\u declspec(dllexport)
#否则
#定义DLL\u导出\u declspec(dllexport)
#恩迪夫
DLL_导出无效函数();
DLL_导出字符**返回字符;
这是空调
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");
}
void函数()
{
char*str=“你好”;
char*str1=“你好吗?”;
ReturnArr=(char**)malloc(sizeof(char*)*2);
对于(;jreferences:i添加了一个.dll作为其显示编译器###错误1错误LNK2001:未解析的外部符号“u declspec(dllimport)char*###*ReturnArr”(_imp?ReturnArr@@3PAPADA)”和“错误2致命错误LNK1120:1未解析的###外部”
如何实际导出全局变量并在应用程序中使用,请告诉我如何在应用程序中将ReturnArr作为全局变量打印
谢谢如果您想让链接器解析ReturnArr导入的变量,您必须将A.LIB添加到链接过程中。有几种方法可以做到这一点
将A.LIB添加到配置属性->链接器->输入中的“附加依赖项”
在Application.c中添加#pragma注释(lib,“a.lib”)
使DLL项目成为EXE项目和EXE项目的依赖项,并将配置属性->链接器->常规“链接库依赖项”设置为“是”
旁注:
您确定需要strcpy(ReturnArr[0],“str”);?可以是
strcpy(ReturnArr[0],str);(str周围没有引号)
如果静态链接到,则不需要加载库和GetProcAddress
您也可以只使用suppress _declspec(dllimport)char**ReturnArr
MYPROC的typedef错误。“function”的返回类型为void,而不是int
如果您想让EXE知道ReturnArr,只需将其作为函数的返回值
你应该试着解释一下你到底想做什么好吧,我必须用Loadlibrary和GetProcAddress来做这件事。你能告诉我怎么做吗that@D.A.如果要手动链接库,则不能使用dllimport
指令。必须使用来检索ReturnArr的地址
@D.A.Danekhail您还需要帮助吗?
#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;
}