Python-C嵌入式细分错误 [英] Python - C embedded Segmentation fault

查看:74
本文介绍了Python-C嵌入式细分错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的问题类似于 Py_initialize/Py_Finalize不能与numpy一起使用两次 .. C中的基本编码:

I am facing a problem similar to the Py_initialize / Py_Finalize not working twice with numpy .. The basic coding in C:

Py_Initialize();
import_array();
//Call a python function which imports numpy as a module
//Py_Finalize()

该程序处于循环中,如果python代码将numpy作为导入模块之一,则会发出段错误.如果我删除numpy,它可以正常工作.

The program is in a loop and it gives a seg fault if the python code has numpy as one of the imported module. If I remove numpy, it works fine.

作为一项临时工作,我尝试不使用Py_Finalize(),但这会导致大量内存泄漏(随着TOP的内存使用量不断增加,观察到了).我试过但不理解我发布的那个链接中的建议.有人可以建议使用numpy等导入时完成呼叫的最佳方法吗?

As a temporary work around I tried not to use Py_Finalize(), but that is causing huge memory leaks [ observed as the memory usage from TOP keeps on increasing ]. And I tried but did not understand the suggestion in that link I posted. Can someone please suggest the best way to finalize the call while having imports such as numpy.

谢谢 桑索什.

推荐答案

我不太确定您似乎不太了解

I'm not quite sure how you don't seem to understand the solution posted in Py_initialize / Py_Finalize not working twice with numpy. The solution posted is quite simple: call Py_Initialize and Py_Finalize only once for each time your program executes. Do not call them every time you run the loop.

我假设您的程序在启动时会运行一些初始化命令(只能运行一次).在此处调用Py_Initialize.永远不要再打电话了.另外,我假设您的程序终止时,它具有一些代码来拆卸东西,转储日志文件等.在那里调用Py_Finalize. Py_Initialize和Py_Finalize不能帮助您在Python解释器中管理内存.请勿为此使用它们,因为它们会导致您的程序崩溃.取而代之的是,使用Python自己的函数来摆脱不需要保留的对象.

I assume that your program, when it starts, runs some initialization commands (which are only run once). Call Py_Initialize there. Never call it again. Also, I assume that when your program terminates, it has some code to tear down things, dump log files, etc. Call Py_Finalize there. Py_Initialize and Py_Finalize are not intended to help you manage memory in the Python interpreter. Do not use them for that, as they cause your program to crash. Instead, use Python's own functions to get rid of objects you don't want to keep.

如果每次运行代码时确实必须创建一个新环境,则可以使用Py_NewInterpreter并创建一个子解释器,然后使用Py_EndInterpreter销毁该子解释器.它们记录在 Python C API 页面底部附近.这与拥有新的解释器的工作原理类似,除了每次子解释器启动时不会重新初始化模块.

If you really MUST create a new environment every time you run your code, you can use Py_NewInterpreter and to create a sub-interpreter and Py_EndInterpreter to destroy that sub-interpreter later. They're documented near the bottom of the Python C API page. This works similarly to having a new interpreter, except that modules are not re-initialized each time a sub-interpreter starts.

这篇关于Python-C嵌入式细分错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆