在DLL中导出变量

用的是VC2005

创建一个Win32 Project,在向导页勾选“DLL”和“Empty project”,添加两个文件
1. win32dll.cpp,内容是
__declspec(dllexport) int AAA;

extern "C" __declspec(dllexport) int __stdcall GetAAA()
{
    return AAA;
}

extern "C" __declspec(dllexport) void __stdcall SetAAA( int aaa )
{
    AAA = aaa;
}

其中 GetAAA/SetAAA 只是用于测试

2. win32dll.def,内容是
LIBRARY win32dll
EXPORTS
    AAA @1 DATA
    GetAAA @2
    SetAAA @3

打开工程属性页 configuration properties->Linker->Input->Module Definition File输入win32dll.def (VC6等不需要这一步)
编译连接就得到 win32dll.dll、win32dll.lib 等等


创建一个空的控制台程序,添加一个文件,内容是
#include <iostream>

// 方法1,使用隐式调用
#pragma comment( lib, "E://test//cpp09//Debug_ansi//win32dll.lib" )
extern __declspec(dllimport) int AAA;
extern "C" __declspec(dllimport) int __stdcall GetAAA();
extern "C" __declspec(dllimport) void __stdcall SetAAA( int aaa );
void foo1()
{
    AAA = 123;
    std::cout << GetAAA() << std::endl;

    SetAAA( 456 );
    std::cout << AAA << std::endl;
}

// 方法2,使用显式调用
#include <windows.h>
void foo2()
{
    HMODULE a = LoadLibraryA( "E://test//cpp09//Debug_ansi//win32dll.dll" );
    if( a )
    {
        int* pAAA = (int*)GetProcAddress( a, "AAA" );
        int (__stdcall *pGetAAA)() = ( int (__stdcall*)() )GetProcAddress( a, "GetAAA" );
        void (__stdcall *pSetAAA)(int) = ( void (__stdcall*)(int) )GetProcAddress( a, "SetAAA" );

        if( pAAA && pGetAAA && pSetAAA )
        {
            *pAAA = 123;
            std::cout << pGetAAA() << std::endl;

            pSetAAA( 456 );
            std::cout << *pAAA << std::endl;
        }
        FreeLibrary( a );
    }
}

int main()
{
    foo1();
    foo2();

    return 0;
}

将win32dll.dll、win32dll.lib 等拷贝到第二个程序下,就可以运行了。

----------------------------------------------------------------------------------------

假如不使用def文件,对于“隐式调用”丝毫不影响;对于“显式调用”,要改为
        int* pAAA = (int*)GetProcAddress( a, "?AAA@@3HA" );
        int (__stdcall *pGetAAA)() = ( int (__stdcall*)() )GetProcAddress( a, "_GetAAA@0" );
        void (__stdcall *pSetAAA)(int) = ( void (__stdcall*)(int) )GetProcAddress( a, "_SetAAA@4" );
这些符号可以通过depends.exe打开相应的dll来查看,depends.exe在www.dependencywalker.com上下载。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值