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()函数

相关推荐
芳草萋萋鹦鹉洲哦31 分钟前
【Windows】tauri+rust运行打包工具链安装
开发语言·windows·rust
权泽谦34 分钟前
R Shiny 交互式网页实战:从零到上线可视化应用
开发语言·信息可视化·r语言
hweiyu001 小时前
Go Fiber 简介
开发语言·后端·golang
会跑的兔子1 小时前
Android 16 Kotlin协程 第二部分
android·windows·kotlin
hhhh明3 小时前
quest2+alvr+steamvr
linux·windows·quest2
ᐇ9594 小时前
Java LinkedList集合全面解析:双向链表的艺术与实战
java·开发语言·链表
码银4 小时前
【数据结构】顺序表
java·开发语言·数据结构
Python私教4 小时前
Python 开发环境安装与配置全指南(2025版)
开发语言·python
百锦再5 小时前
第12章 测试编写
android·java·开发语言·python·rust·go·erlang
无敌最俊朗@5 小时前
C++ 并发与同步速查笔记(整理版)
开发语言·c++·算法