如何在 C++ 中操作 pybind11::dict

Ant*_*ten 3 c++ python pybind11

我正在用 C++ 编写一个接受 dict 的模块。

如何在 C++ 中操作 pybind11::dict

#include <pybind11/pybind11.h>
#include<iostream>
#include <pybind11/stl.h>
#include<map>

using namespace std;

namespace py = pybind11;

int main() {

    py::dict dict;
    dict["a"] = 1; // throws exception error - ptyes.h Line 546
    dict["b"] = 2; // throws exception error - ptyes.h Line 546

    for (auto item : dict)
    {
        std::cout << "key: " << item.first << ", value=" << item.second << std::endl;
    };
    system("pause");
    return 0;

}
Run Code Online (Sandbox Code Playgroud)

小智 5

您的代码不是一个模块,它是一个使用 Python 解释器的独立 C++ 程序,您的工作是初始化 Python 解释器,就像在https://pybind11.readthedocs.io/en/stable/advanced/embedding上编写的那样.html

像这样:

#include <pybind11/pybind11.h>
#include <pybind11/embed.h> // <= You need this header
#include<iostream>
#include <pybind11/stl.h>
#include<map>

using namespace std;

namespace py = pybind11;

int main() {
    py::scoped_interpreter guard{}; // <= Initialize the interpreter
    py::dict dict;
    dict["a"] = 1; // throws exception error - ptyes.h Line 546
    dict["b"] = 2; // throws exception error - ptyes.h Line 546

    for (auto item : dict)
    {
        std::cout << "key: " << item.first << ", value=" << item.second << std::endl;
    };
    system("pause");
    return 0;

}
Run Code Online (Sandbox Code Playgroud)

当您实现模块时,您不需要 py::scoped_interpreter 行。

有趣的事实:如果您使用字符串作为值或大整数作为值,您的代码会工作得更好一些(可能在某些时候仍然会崩溃)。通过使用像 1 和 2 这样的小整数,你的代码会达到 Python 的小整数优化(https://github.com/python/cpython/blob/3.8/Objects/longobject.c#L318)并且崩溃得更快。