windows下dll的动态调用方法
程序员文章站
2022-06-25 20:17:13
...
- 编写动态库
libAAA.h
#pragma once
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#if defined(WIN32) || defined(_WIN32)
#define LIB_EXPORT _declspec(dllexport)
#else
#define LIB_EXPORT __attribute__((visibility("default")))
#endif
extern "C" LIB_EXPORT int fnlibAAA_test(void);
extern "C" LIB_EXPORT int fnlibAAA_sum(int a,int b);
libAAA.cpp
#include "libAAA.h"
LIB_EXPORT int fnlibAAA_test(void)
{
return 55;
}
LIB_EXPORT int fnlibAAA_sum(int a, int b)
{
return (a + b);
}
- 调用方法
main.cpp
#include <iostream>
#include <windows.h>
typedef int(*MYtestN)(void);
typedef int(*MYsumN)(int a,int b);
int main()
{
int ret = 0;
HMODULE dlllHandle = NULL;
dlllHandle = ::LoadLibrary(L"D:\\myStudy\\c++Demo\\fnlibAAA\\x64\\Release\\fnlibAAA.dll");
if (dlllHandle)
{
MYtestN testApi = (MYtestN)::GetProcAddress(dlllHandle, "fnlibAAA_test");
if (!testApi)
{
std::cout << "GetProcAddress testApi fail\n";
}
else
{
ret= testApi();
std::cout << "testApi result: " << ret << "\n";
}
MYsumN sumApi = (MYsumN)::GetProcAddress(dlllHandle, "fnlibAAA_sum");
if (!sumApi)
{
std::cout << "GetProcAddress sumApi fail\n";
}
else
{
ret = sumApi(10,20);
std::cout << "sumApi result: " << ret << "\n";
}
}
else
{
std::cout << "load lib fail\n";
}
std::cout << "game over !!! \n";
system("pause");
return 0;
}
- 结果