windows c dll的创建与调用

时间:2022-06-23 00:44:05

DLL代码:

// TestDynamic.cpp: implementation of the TestDynamic class.
//
////////////////////////////////////////////////////////////////////// #include "TestDynamic.h"
#include <windows.h> //////////////////////////////////////////////////////////////////////
// Construction/Destruction
////////////////////////////////////////////////////////////////////// BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
} __stdcall int Plus(int x, int y)
{
return x + y;
} __stdcall int Sub(int x, int y)
{
return x - y;
} __stdcall int Mul(int x, int y)
{
return x * y;
} __stdcall int Div(int x, int y)
{
return x / y;
}
// TestDynamic.h: interface for the TestDynamic class.
//
////////////////////////////////////////////////////////////////////// #if !defined(AFX_TESTDYNAMIC_H__5BBAD36E_608D_4D94_B6D6_19404806F6AE__INCLUDED_)
#define AFX_TESTDYNAMIC_H__5BBAD36E_608D_4D94_B6D6_19404806F6AE__INCLUDED_ #if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000 extern "C" __declspec(dllexport) __stdcall int Plus(int x, int y); extern "C" __declspec(dllexport) __stdcall int Sub(int x, int y); extern "C" __declspec(dllexport) __stdcall int Mul(int x, int y); extern "C" __declspec(dllexport) __stdcall int Div(int x, int y); #endif // !defined(AFX_TESTDYNAMIC_H__5BBAD36E_608D_4D94_B6D6_19404806F6AE__INCLUDED_)

调用程序主代码:

// TestDll.cpp : Defines the entry point for the console application.
// 隐式调用 #include "stdafx.h" #pragma comment(lib,"testDynamic.lib"); extern "C" __declspec(dllimport) __stdcall int Plus(int x, int y);
extern "C" __declspec(dllimport) __stdcall int Sub(int x, int y);
extern "C" __declspec(dllimport) __stdcall int Mul(int x, int y);
extern "C" __declspec(dllimport) __stdcall int Miv(int x, int y); int main(int argc, char* argv[])
{
int t = Plus(,);
printf("%d\n",t);
return ;
}
// TestDll.cpp : Defines the entry point for the console application.
// 显式调用 #include "stdafx.h"
#include <windows.h> typedef int (__stdcall *lpPlus)(int, int);
typedef int (__stdcall *lpSub)(int, int);
typedef int (__stdcall *lpMul)(int, int);
typedef int (__stdcall *lpDiv)(int, int); int main(int argc, char* argv[])
{
lpPlus myPlus;
lpSub mySub;
lpMul myMul;
lpDiv myDiv; HINSTANCE hModule = LoadLibrary("testDynamic.dll");
myPlus = (lpPlus)GetProcAddress(hModule, "Plus"); int x = myPlus(,);
printf("%d\n",x); return ;
}

PS:注意__stdcall如果DLL中没有定义为__stdcall在调用时就不要用