1.mingw和msvc
g++ -fpic HelloWorld.cpp -shared -o test.dll
g++ -L . -ltest .\test.cpp
注意-L后面的.挨不挨着都行,-l不需要-ltest.dll,只需要-ltest
2.dll.cpp
extern "C" {
__declspec(dllexport) int __stdcall add(int a, int b) {
return a + b;
}
}
3.dll.h
extern "C" {
__declspec(dllexport) int __stdcall add(int a, int b);
}
4.test.c:必须要 #include "./HelloWorld.h",python则不需要
#include <stdio.h>
#include "./HelloWorld.h"
extern int add(int a, int b);
int main(){
printf("\n[%d]\n", add(12, 5));
return 0;
}
5.python:main.py:经常找不到库,如何解决
1)绝对路径
2)os.add_dll_directory包含库的搜索路径
3)3.8以上版本,还是找不到就需要加上winmode=0
import ctypes
import os
a = ctypes.WinDLL( 'test.dll' , winmode=0).add(12, 5)
print(a)
os.add_dll_directory("D:\\code\\thirdparty\\Chess\\cpp")
a = ctypes.WinDLL("test.dll").add(12, 5)
print(a)
6.python如果是cdecl就用CDLL()函数