【问题标题】:C++ and pybind11: type_caster support for std::span?C++ and pybind11: type_caster support for std::span?
【发布时间】:2022-12-27 12:41:38
【问题描述】:

I wish to pass a Python numpy array to this C++ function:

int data(std::span<int> x) { return x.size(); }

Is it possible to write a custom type caster for pybind11 that supports this signature?

pybind already has good support for vector&lt;int&gt;, but I would like to add support for a zero-copy version of vector, i.e. pass by reference.

It looks like there are some clues on how to do this here.

【问题讨论】:

    标签: c++ c++17 pybind11


    【解决方案1】:

    There's two questions here, so I'll answer them each individually:

    1. It is certainly possible to write a custom type caster for std::span -- my own implementation based off the pybind11 type caster for abseil's span can be found here. I haven't gotten around to submitting a patch upstream yet, but someone else is also interested in this (see github discussion).

    2. Most of the pybind11 STL type casters make copies of their sequences, so it's likely that any future std::span casters (like mine) are also going to make copies. That doesn't mean it's impossible -- the abseil span implementation does have a specialization where they would convert a span to a python buffer if it was a basic type.

    【讨论】:

      猜你喜欢
      • 2022-12-28
      • 2023-01-12
      • 1970-01-01
      • 1970-01-01
      • 2020-10-07
      • 1970-01-01
      • 1970-01-01
      • 2021-03-02
      • 1970-01-01
      相关资源
      最近更新 更多