我有一个DLL
A.DLL
这是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)
#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");
}
现在我有Application.c将使用DLL
#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中:我添加了A.dll它显示我编译器##错误错误1错误LNK2001:未解析的外部符号“_declspec(dllimport)char * ## * ReturnArr”( imp?ReturnArr @@ 3PAPADA)“和“错误2致命错误LNK1120:1未解决## externals”
我怎么能实际导出一个全局变量并在我的应用程序中使用,告诉我如何在我的应用程序中将ReturnArr实际打印为全局变量
谢谢
1 回答
如果希望链接器解析ReturnArr导入的变量,则必须将A.LIB添加到链接进程 . 有几种方法可以做到这一点 .
在配置属性 - >链接器 - >输入中将A.LIB添加到"additionnal dependecies"
在Application.c中添加#pragma comment(lib,"a.lib")
使DLL项目成为EXE项目和EXE项目的依赖项,并将Configuration属性 - > linker-> General "Link Library dependencies"设置为yes .
附注:
你确定你想要strcpy(ReturnArr [0],"str"); ?可以是strcpy(ReturnArr [0],str); (没有str附近的报价)
如果静态链接到A,则不需要LoadLibrary和GetProcAddress .
你也可以只是压制_declspec(dllimport)char ** ReturnArr;
MYPROC的typedef错误 . "function"的返回类型为void,而不是int
如果您希望EXE了解ReturnArr,只需将其作为函数的返回值即可!
You should try to explain what exactly you are trying to do