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

使用ctypes导入含iostream的C++ DLL至Python时加载失败求助

MinGW64编译含的C++ DLL无法被Python ctypes加载的问题

问题描述

在Windows 10 x64环境下,使用Python 3.10.8的ctypes模块加载MinGW64的g编译的C DLL时出现异常:

  • 当代码包含<ostream>、<cmath>等头文件时,DLL可正常加载并调用
  • 替换为包含<iostream>头文件后,触发错误:Could not find module 'C:\Test\foo.dll' (or one of its dependencies). Try using the full path with constructor syntax.

已排查操作

  • 确认DLL路径完全正确
  • 尝试切换所有C++标准进行编译
  • 调整导出声明为extern "C" __declspec(dllexport)格式
  • 采用官方推荐的链接编译方式
  • 使用Dependency Walker检测到近百个缺失依赖,但无明确指向,无法定位核心原因

复现代码示例

可正常编译运行的a.cpp

#include <ostream>
extern "C" void Print()
{
    printf("Hello!");
}

编译后加载报错的a.cpp

#include <iostream>
extern "C" void Print()
{
    printf("Hello!");
}

调用DLL的Python代码b.py

from ctypes import *
core = cdll.LoadLibrary("C:/Test/c.dll")
core.Print()

编译用makefile

main:
    g++ -shared -o c.dll a.cpp
    python3 -B b.py

解决方案

1. 静态链接标准库

编译时添加-static-libgcc -static-libstdc++参数,将C和C++标准库静态嵌入DLL,消除对MinGW动态库的依赖:

g++ -shared -o c.dll a.cpp -static-libgcc -static-libstdc++

2. 添加MinGW路径到系统环境变量

若不想静态链接,可将MinGW64安装目录下的bin文件夹(例如C:\mingw64\bin)添加到系统PATH中,让系统能找到DLL依赖的libstdc++-6.dll等动态库。

3. 准确定位缺失依赖

Dependency Walker在Windows 10下可能误报系统依赖,可通过以下方式确认真实缺失:

  • 用Process Monitor跟踪Python加载DLL时的文件查找流程,定位真正找不到的依赖库
  • 执行dumpbin /dependents c.dll(需安装Visual Studio工具集),查看更准确的依赖列表

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 21:10:36