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