首页 > 代码库 > DLL基础

DLL基础

Visual C++在创建DLL导出函数时,可能会对原始的函数名做修改。例如:

int WINAPI Add(int nLeft, int nRight)

导出后的函数名称是_Add@8。

下面两种方法可使编译器不对导出函数名称做修改:

  1. 使用def文件
  2. 在代码中添加:#pragma comment(linker, "/export:Add=_Add@8")

MyLib.h

#ifdef MYLIB_EXPORTS

#define MYLIBAPI extern "C" __declspec(dllexport)

#else

#define MYLIBAPI extern "C" __declspec(dllimport)

#endif

MYLIBAPI int g_nResult;

//MYLIBAPI int Add(int nLeft, int nRight);
MYLIBAPI int WINAPI Add(int nLeft, int nRight);

MyLibFile1.cpp

#include <windows.h>
#include "MyLib.h"

#pragma comment(linker, "/export:Add=_Add@8")

int g_nResult;

//int Add(int nLeft, int nRight)
int WINAPI Add(int nLeft, int nRight)
{
    g_nResult = nLeft + nRight;
    return g_nResult;
}

MyLib.def

EXPORTS
  Add

MyExeFile1.cpp

#include <windows.h>
#include <strsafe.h>
#include <stdlib.h>

#include "..\MyLib.h"

int WINAPI WinMain(HINSTANCE , HINSTANCE , LPTSTR , int)
{
    int nLeft = 10, nRight = 25;

    TCHAR sz[100];
    StringCchPrintf(sz, sizeof(sz)/sizeof(sz[0]), TEXT("%d + %d = %d"),
        nLeft, nRight, Add(nLeft, nRight));
    MessageBox(NULL, sz, TEXT("Calculation"), MB_OK);

    StringCchPrintf(sz, sizeof(sz)/sizeof(sz[0]),
        TEXT("The result from the last Add is: %d"), g_nResult);
    MessageBox(NULL, sz, TEXT("Last Result"), MB_OK);

    return 0;
}