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

时间:2019-07-13 18:22:04

标签: python c++ pybind11

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

如何在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;

}

1 个答案:

答案 0 :(得分:0)

您的代码不是模块,它是使用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;

}

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

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