Windows10下C++嵌入Python3.12初始化失败,如何配置PyConfig?
解决Python 3.12嵌入C++时的初始化失败问题
当启用isolated模式嵌入Python时,Python会禁用自动路径探测,必须手动指定核心路径属性才能找到标准库与编码组件,解决"failed to get the Python codec of the filesystem encoding"错误需要配置以下PyConfig属性:
home:指定Python安装根目录,让Python定位标准库所在的Lib文件夹config.home = Py_DecodeLocale(L"D:\\Programs\\Python\\Python312", NULL);prefix与exec_prefix:Windows标准安装下这两个路径与home一致,用于标识Python的安装前缀目录config.prefix = Py_DecodeLocale(L"D:\\Programs\\Python\\Python312", NULL); config.exec_prefix = Py_DecodeLocale(L"D:\\Programs\\Python\\Python312", NULL);program_name:指定调试版Python可执行文件的完整路径,帮助Python识别自身执行环境config.program_name = Py_DecodeLocale(L"D:\\Programs\\Python\\Python312\\python_d.exe", NULL);
完整初始化示例代码
#include <Python.h> int main() { PyConfig config; PyConfig_InitIsolatedConfig(&config); // 配置Python核心路径 config.home = Py_DecodeLocale(L"D:\\Programs\\Python\\Python312", NULL); config.prefix = Py_DecodeLocale(L"D:\\Programs\\Python\\Python312", NULL); config.exec_prefix = Py_DecodeLocale(L"D:\\Programs\\Python\\Python312", NULL); config.program_name = Py_DecodeLocale(L"D:\\Programs\\Python\\Python312\\python_d.exe", NULL); // 若无需严格隔离环境,可关闭isolated模式(可选) // config.isolated = 0; int init_result = Py_InitializeFromConfig(&config); if (init_result != 0) { wprintf(L"初始化失败,错误码:%d\n", init_result); PyConfig_Clear(&config); return 1; } // 测试执行Python代码 PyRun_SimpleString("print('嵌入Python执行成功!')"); Py_Finalize(); PyConfig_Clear(&config); return 0; }
注意事项
- 所有通过
Py_DecodeLocale分配的字符串,无需手动释放,PyConfig_Clear会自动完成资源清理 - 确保项目已正确链接调试版Python库
python312_d.lib,包含目录指向D:\Programs\Python\Python312\include,库目录指向D:\Programs\Python\Python312\libs - 调试版DLL
python312_d.dll需放置在项目输出目录,或通过系统路径访问
内容的提问来源于stack exchange,提问作者Mike Finch
相关产品推荐
相关产品推荐

