如何在主函数中使用 boost::python::dict 或元组?

Gau*_*uss 4 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;
}
Run Code Online (Sandbox Code Playgroud)

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

Hug*_*rrá 5

在使用任何 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;
}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

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

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