dll导出全局变量

           dll 导出全局变量的使用 加上 DATA 标识、

写个简单的 dll

#include <stdio.h>

int a;

void show()
{
	printf("%d\n",a);
}
编译链接

C:\>cl 1.c /c
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.30319.01 for 80x86
Copyright (C) Microsoft Corporation.  All rights reserved.

1.c

C:\>link 1.obj /dll /EXPORT:a,DATA /EXPORTS:show
Microsoft (R) Incremental Linker Version 10.00.30319.01
Copyright (C) Microsoft Corporation.  All rights reserved.

   Creating library 1.lib and object 1.exp

然后在 exe 里面引用的时候

#include <stdio.h>
int __declspec(dllimport) a;
void show();
int main()
{
    a = 9;
    show();
    return 0;
}
对于使用 DATA标识导出的变量引用的时候必须使用 extern __declspec(dllimport)  MSDN里面有说明

The DATA keyword specifies that the exported item is a data item. The data item in the client program must be declared using extern __declspec(dllimport).

然后就可以直接 对这个变量赋值啥的了 就像在 dll 中操作这个变量一样。。。

如果不这样做 比如直接 extern int a;

最后 a 被赋值的是 dll 中变量 a 的地址 实际上是装载的时候使用函数 GetProcAddress 来赋值a的,,

使用 dllimport 之后 其实是编译器在编译的时候 知道这个是 dll 导入的变量 然后就会在生成汇编代码的时候 向其指针指向的内存中写值。。。。



你可能感兴趣的:(dll导出全局变量)