在 C++ 中嵌入 Python 在运行时崩溃 [英] Embedding Python in C++ crashes during running-time

查看:248
本文介绍了在 C++ 中嵌入 Python 在运行时崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题我已经问了太久了.现在我搜索了这个,它已经工作了一段时间,但是然后它在一个随机的地方坠毁.我认为问题是死锁什么的.

I've been around this question for way too long. Now I searched this and it was working for a while but it then crashed at a random place. I think that the problem is a deadlock or something.

所以请有人告诉我我做错了什么:

So please, someone tell me what I'm doing wrong:

  1. 我创建了一个全局变量:

  1. I make a global variable:

static int gil_init = 0; 

  • 在程序开始时,我调用了 Py_Initialize().这个启动函数在一个会话中被多次调用,但由于 Py_Initialize() 是一个非操作,如果 Python 已经初始化,我认为这里没有问题.

  • At the start of the program I call Py_Initialize(). This start function is called multiple times in one session but since Py_Initialize() is a non-op if Python is already initialized I don't think there's a problem here.

    从三个函数中,我对 Python/C API 函数进行了大量调用 -py_embed(...)(一次只有一个调用).下一个代码出现在从每个线程调用的 py_embed() 函数中:

    From three functions I make lots of calls into the Python/C API function -py_embed(...) (there's only one at a time calling). The next code is present in the py_embed() function that is called from each thread:

    if (!gil_init) {
        gil_init = 1;
        PyEval_InitThreads();
        PyEval_SaveThread();
    }
    state = PyGILState_Ensure();
    // Call Python/C API functions...
    //pValue= PyObject_CallObject(pFunc, pArgs2);  Crash is always given here
    PyGILState_Release(state);
    

  • 哦,崩溃发生在其中一个函数中,但不是我第一次调用它,这很奇怪.这就是为什么我说它在运行时间的随机位置.

    Oh and the crash takes place in one of the functions, but not the first time I call it which is strange. That's why I said its at a random place during running time.

    理论上,基于 C Api 的参考手册它应该可以工作..我做错了什么?

    In theory, and based in the reference manual of the C Api it should be working.. What am I doing wrong?

    我不调用 Py_Finalize() 因为我遇到的这个问题

    推荐答案

    我想我已经解决了(不能肯定,但直到现在还没有崩溃).

    I think I solved it (can't say for sure but until now it hasn't crashed).

    问题是我正在取消引用一些借用的引用.我注意到这一点是因为某些对象的引用计数是 2 或 3.

    The problem was that I was dereferenciating some borrowed references. I noticed this because the reference count of some objects were 2 or 3.

    这篇关于在 C++ 中嵌入 Python 在运行时崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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