VC++ 創建及調用Dll


一、_stdcall 

被這個關鍵字修飾的函數,其參數都是從右向左通過堆棧傳遞的(__fastcall 的前面部分由ecx,edx傳), 函數調用在返回前要由被調用者清理堆棧。

這個關鍵字主要見於Microsoft Visual C、C++。GNU的C、C++是另外一種修飾方式:__attribute__((stdcall))

1.

MathFunsStd.cpp:

 int _stdcall add(int a, int b)
{
return a+b;
}

int _stdcall subtract(int a, int b)
{
return a-b;
}

int _stdcall multiple(int a, int b)
{
return a*b;
}

MathFunsStd.def:

LIBRARY MathFunsStd

EXPORTS
add
subtract
multiple

2.MathFuns.cpp

int add(int a, int b)
{
return a+b;
}

int subtract(int a, int b)
{
return a-b;
}

int multiple(int a, int b)
{
return a*b;
}

MathFuns.def

LIBRARY MathFuns

EXPORTS
add
subtract
multiple

3.UseHeaderAPI

MathFunsUseHeader.h

#ifdef MathFunsUseHeaderAPI 
#else
#define MathFunsUseHeaderAPI _declspec(dllimport)
#endif

MathFunsUseHeaderAPI int add(int a,int b);
MathFunsUseHeaderAPI int subtract(int a,int b);
MathFunsUseHeaderAPI int multiple(int a, int b);


#define MathFunsUseHeaderAPI _declspec(dllexport)
#include "MathFunsUseHeader.h"

MathFunsUseHeader.cpp

int add(int a, int b)
{
return a+b;
}

int subtract(int a, int b)
{
return a-b;
}

int multiple(int a, int b)
{
return a*b;
}

三、調用

 
/*加載dll函數調用方式為默認調用方式*/
HINSTANCE hInst = LoadLibrary(L"MathFuns.dll");
if(!hInst)
{
printf("加載MathFuns.dll失敗!\n");
}
typedef int (*MathFunsAPI)(int a, int b);//定義函數指針變量類型
MathFunsAPI Add = (MathFunsAPI)::GetProcAddress(hInst,"add");
printf("5+3=%d\n",Add(5,3));
::FreeLibrary(hInst);

       //調用dll函數調用方式為_stdcall
HINSTANCE hInstStd = ::LoadLibrary(L"MathFunsStd.dll");
if(!hInstStd)
{
printf("加載MathFunsStd.dll失敗!\n");
}
typedef int (_stdcall *MathFunsStdAPI)(int a, int b);//定義函數指針變量類型
MathFunsStdAPI AddStd = (MathFunsStdAPI)::GetProcAddress(hInstStd,"add");
printf("5+3=%d\n",AddStd(5,3));
::FreeLibrary(hInst);

return 0;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM