如何在C++中操纵PybDun11:DICT

2024-10-01 00:14:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个C++的模块,接受DIST./P><如何操纵C++中的PYBIDN11::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;

}

Tags: 模块pyincludedistlineexceptionerroritem
1条回答
网友
1楼 · 发布于 2024-10-01 00:14:47
<>你的代码不是一个模块,它是一个使用Python解释器的独立C++程序,它的工作是初始化Python解释器,就像它写在{A1}

上一样。

像这样:

#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_解释器行。在

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

相关问题 更多 >