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

How to use boost::python::dict or tuple in main function?

当我在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中使用它们时,没问题,有什么问题吗?

在使用任何 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 字符串是不可变的) . 段错误(未调用 Py_Initilize 时)发生在该函数内部,因为 Python 需要查询其运行时环境以检查字符串,但一旦未加载环境,它就会崩溃。

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