如何在main函数中使用boost :: python :: dict或tuple?

时间:2017-07-25 14:43:33

标签: boost-python

当我在main函数中使用boost :: python :: tuple或boost :: python :: dict时,程序崩溃了!

#define BOOST_PYTHON_STATIC_LIB
#include <boost/python.hpp>
#include <iostream>
#include <boost/python/tuple.hpp>
#include <boost/python/dict.hpp>

//using namespace std;
using namespace boost::python;

int main()
{
    //tuple x;
    //x = make_tuple(object(0),object(1));
    dict x;
    x["123"] = 3;
    return 0;
}

但是当我在.dll中使用它们时,它没问题,那是什么问题?

1 个答案:

答案 0 :(得分:1)

在使用任何python对象之前调用Py_Initialize()初始化解释器是必要的:

#define BOOST_PYTHON_STATIC_LIB
#include <boost/python.hpp>
#include <iostream>
#include <boost/python/tuple.hpp>
#include <boost/python/dict.hpp>

//using namespace std;
using namespace boost::python;

int main()
{
    Py_Initialize();
    dict x;
    x["123"] = 3;
    return 0;
}

Boost Python为C ++与Python的接口提供了很多功能,但也提供了一些使用C ++在更高级别创建C扩展的功能。上面的代码完全符合下面的代码:

#include <Python.h>
#include <dictobject.h>

int main(int argc, char *argv[])
{
    Py_Initialize();
    PyObject *d = PyDict_New();
    PyDict_SetItemString(d, "123", PyLong_FromLong(3));
    return 0;
}

PyDict_SetItemString内部调用PyUnicode_InternInPlace基本上尝试使用已存在的字符串,否则会创建一个新字符串(请记住python字符串是不可变的)。 segfault(当没有调用Py_Initilize时)发生在这个函数内部,因为Python需要查询它的运行时环境以检查字符串,但是一旦环境未加载,它就会崩溃。

在创建.dll时,没有必要显式调用Py_Initilize,因为它是在初始化期间已经调用它的解释器中导入的。