You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows下ctypes无法加载含pthread_create的.so文件求助

解决Windows下Python ctypes加载含pthread的.so库报错问题

问题背景

在Windows 10、Python 3.10环境中:

  • ctypes可正常加载未调用pthread_create()的.so文件
  • 当.so源码中使用pthread_create()时,加载会抛出FileNotFoundError(实际是找不到依赖的pthread动态库)
  • 仅声明pthread_t变量时可正常加载,编译为独立exe可正常运行
  • 编译已使用-lpthread参数,尝试多种编译方式、Python用绝对路径/os.path.join加载均无效

相关代码片段:

C代码

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void some_func(args){
    pthread_t th_1, th_2, th_3, th_4;
    void* func_to_use_in_threads(void *arg) { /* 函数内容 */ }
    pthread_create(&th_1,NULL,func_to_use_in_threads,&arg);
    // 其他pthread_create及pthread_join调用
}

原编译命令

gcc -fPIC -shared -o the_name.so the_name.c -lpthread

Python加载代码

import ctypes
some_lib=ctypes.CDLL('file_path\\file_name.so')

解决办法

1. 静态链接pthread库(推荐)

修改编译命令,强制静态链接pthread,将pthread代码打包进.so文件,避免依赖外部动态库:

gcc -fPIC -shared -o the_name.so the_name.c -Wl,-Bstatic -lpthread -Wl,-Bdynamic
  • -Wl,-Bstatic 告诉链接器对后续的库采用静态链接
  • -lpthread 指定静态链接pthread库
  • -Wl,-Bdynamic 切回动态链接其他系统库(避免不必要的静态依赖)

2. 动态链接时补充pthread依赖文件

如果坚持使用动态链接,需要将MinGW安装目录下的libwinpthread-1.dll文件复制到以下任意位置:

  • Python脚本的运行目录
  • Windows系统环境变量PATH包含的目录(如C:\Windows\System32)

Windows下动态库加载时会优先从当前目录和PATH路径查找依赖的dll,而MinGW的pthread动态库默认不在系统PATH中,这是导致加载失败的核心原因。

3. 验证库的依赖情况

用MinGW的objdump工具检查.so的依赖,确认pthread的链接方式:

objdump -x the_name.so | grep pthread
  • 若输出包含libwinpthread-1.dll,说明是动态链接,需按方法2处理
  • 若输出无动态库依赖,说明静态链接成功,可直接用Python加载

内容的提问来源于stack exchange,提问作者undeadpresident

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 05:12:04