从Python调用执行Python代码的C++函数时出现free()无效指针错误
问题根源
- 解释器冲突:从Python进程调用动态库时,当前进程已有运行中的Python解释器,重复加载libpython并调用
Py_Initialize()会导致内存管理冲突,触发无效指针错误。 - 头文件错误:
runner.h直接包含runner.cpp,编译时会造成符号重复定义,引发隐性内存问题。 - 链接缺失:编译命令未链接
dl库(-ldl),dlopen等函数调用可能出现未定义行为。
修复方案
方案1:复用当前进程的Python解释器(推荐)
既然是从Python进程调用,无需重新加载libpython或初始化解释器,直接使用现有环境:
修改runner.cpp
#include <iostream> #include <Python.h> void execute_Prog730(std::string program) { std::cout << "Running Engine" << std::endl; // 直接调用API,当前进程已有活跃的解释器 PyRun_SimpleString(program.c_str()); }
修改runner.h
去掉对cpp文件的包含,只保留函数声明:
#include <string> void execute_Prog730(std::string program);
修正编译命令
用python3-config自动获取编译和链接参数:
g++ -o main.so --shared -fPIC main.cpp runner.cpp $(python3-config --cflags --ldflags)
方案2:使用子解释器(如需独立环境)
如果必须在动态库中运行独立的Python环境,可创建子解释器而非重新初始化:
#include <iostream> #include <Python.h> void execute_Prog730(std::string program) { std::cout << "Running Engine" << std::endl; // 创建子解释器 PyThreadState* sub_state = Py_NewInterpreter(); if (sub_state) { PyRun_SimpleString(program.c_str()); // 销毁子解释器 Py_EndInterpreter(sub_state); } }
验证
修改后运行main.py,应能正常输出hello,无内存错误。
内容的提问来源于stack exchange,提问作者Lakshit Karsoliya
相关产品推荐
相关产品推荐

