mingw如何制作动态库附python调用

1.mingw和msvc

bash 复制代码
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

bash 复制代码
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()函数

相关推荐
cui_ruicheng2 分钟前
Python从入门到实战(八):封装、多态与抽象类
开发语言·python
apihz3 分钟前
台风实时与历史详情查询免费 API 接口完整教程
android·开发语言·tcp/ip·dubbo·台风·天气预报
知无不研16 分钟前
c语言和c++中的静态关键字
开发语言·c++·静态关键字
bksczm31 分钟前
Linux之信号量(POSIX标准)
java·开发语言
吠品42 分钟前
PHP里取月份最后一天的几种方式
java·开发语言·eureka
CallmeFoureyes44 分钟前
使用 C# 提取 Word 文档中的表格数据
开发语言·c#·word
gugucoding1 小时前
2. 【Java】搭建Java开发环境
java·开发语言
多加点辣也没关系1 小时前
JavaScript|第9章:对象 — 基础
开发语言·javascript·ecmascript
2601_949818091 小时前
Vector从入门到应用(C++ STL动态数组万字全解
开发语言·c++
blueman88881 小时前
qt5-serialbus详细解析
开发语言·网络·qt