我是一名经验丰富的Python程序员,正在try 学习C++来加快一些项目的速度. 将py::tuple传递给函数,如何访问元素?

这是我正在制作的一个类的构造函数,用于保存视频中的图像.

Buffer::Buffer(int size, py::tuple hw_args_) {

unsigned int frame_height = get<0>(hw_args_);
unsigned int frame_width = get<1>(hw_args_);

Buffer::time_codes = new int[size];
Buffer::time_stamps = new string[size];
Buffer::frames = new unsigned char[size][hw_args[0]][hw_args[1]];

if ((Buffer::time_codes && Buffer::time_stamps) == 0) {
    cout << "Error allocating memory\n";
    exit(1);
}

}

这给我带来了一个错误"重载函数‘get’的实例没有匹配参数列表,参数类型是pybind 11::tuple"

我还try 过以这种方式设置框架高度和宽度.

unsigned int frame_height = hw_args_[0];
unsigned int frame_width = hw_args_[1];

这会给出一个错误"不存在从‘pybind 11::Details:tuple_accessor’到‘united int’的合适转换函数"

我很困惑,我似乎只能找到有关在C++中创建二元组的信息,而无法从Pythind 11/ Python中访问它们.

推荐答案

py::tuple有一个operator[],它返回一个detail::tuple_accessor,它有一个.cast作为任何py::object

uint32_t frame_height = hw_args_[0].cast<uint32_t>();

您可以从pybind11 tests开始判断其使用情况

[](const py::tuple &tup) {
  if (py::len(tup) != 4) {
    throw py::cast_error("Invalid size");
  }
  return SimpleStruct{tup[0].cast<bool>(),
                      tup[1].cast<uint32_t>(),
                      tup[2].cast<float>(),
                      tup[3].cast<long double>()};
        }

Python相关问答推荐

遵循轮廓中对象方向的计算线

在内部列表上滚动窗口

Python daskValue错误:无法识别的区块管理器dask -必须是以下之一:[]

如何使用symy打印方程?

Odoo 14 hr. emergency.public内的二进制字段

使用新的类型语法正确注释ParamSecdecorator (3.12)

为什么tkinter框架没有被隐藏?

如何检测背景有噪的图像中的正方形

如何让剧作家等待Python中出现特定cookie(然后返回它)?

使用miniconda创建环境的问题

在Python argparse包中添加formatter_class MetavarTypeHelpFormatter时, - help不再工作""""

Django REST Framework:无法正确地将值注释到多对多模型,不断得到错误字段名称字段对模型无效'<><>

使用groupby方法移除公共子字符串

删除marplotlib条形图上的底边

搜索按钮不工作,Python tkinter

Gekko中基于时间的间隔约束

Python日志(log)模块如何在将消息发送到父日志(log)记录器之前向消息添加类实例变量

如何合并具有相同元素的 torch 矩阵的行?

如何在一组行中找到循环?

有没有办法在不先将文件写入内存的情况下做到这一点?