Dev-cpp新建DLL项目。
dllmain.cpp
#include "dll.h"
#include <windows.h>
int add(int a, int b) {
return a + b;
}
dll.h
#ifndef _DLL_H_
#define _DLL_H_
extern "C" __declspec(dllexport) int add(int a, int b);
#endif
调用DLL,将dll拷贝至调用的项目路径中。
调用代码:
#include <iostream>
#include<Windows.h>
#include "dll.h"
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
printf("Hello, World!");
HMODULE h = NULL;//创建一个句柄h
h = LoadLibrary("dlltest.dll");
if (h == NULL)//检测是否加载dll成功
{
printf("加载DLLTest1.dll动态库失败\n");
return -1;
}
typedef int(*AddFunc)(int, int); // 定义函数指针类型
AddFunc add;
add = (AddFunc)GetProcAddress(h, "add");
int sum = add(100, 20);
printf("动态调用的结果%d\n", sum);
return 0;
}
python调用:
from ctypes import *
#----------以下四种加载DLL方式皆可—————————
# pDLL = WinDLL("./myTest.dll")
# pDll = windll.LoadLibrary("./myTest.dll")
# pDll = cdll.LoadLibrary("./myTest.dll")
pDll = CDLL("./dlltest.dll")
#调用动态链接库函数
res = pDll.add(100,2)
#打印返回结果
print(res)