0

I am starting to use Pybind11. I am planning to use Pybind11 in a complex project for exposing c++ structures to python, will be helpful to see an example showing how to expose populate from python an array using the following structures:

template <typename T>
struct point;

template <typename T>
struct quaternion;

template <typename T>
struct point{
T _x, _y, _z;
};

template <typename T>
struct quaternion{
T _a, _b_i, _c_j, _d_k;
};

It is a good idea to use std::shared_ptr pointers. How to use std::smart_ptr with pybind11? In more concrete terms, I want to be able of populating the array from python and once the population is complete, I want to be capable of passing a range of pointers(std::smart_ptr) pointing to a region of the array from python to a routine in C++ to do something else with the data. It could be passing a pointer to the beginning and another the end of a chunk of data in the array scan the data using pointer arithmetics.

Disclaimer: I don't know if Pybin11 might be using std::shared_ptr under the hood by default.

3
  • What is std::smart_ptr? Do you mean smart pointers in general? Commented Jun 17, 2020 at 13:00
  • yes, in particular, std::share_ptr en.cppreference.com/w/cpp/memory/shared_ptr Commented Jun 17, 2020 at 13:23
  • can you provide examples of what you're expecting the python code that is consuming the bindings to look like? Commented Jun 17, 2020 at 16:40

1 Answer 1

0

I believe that for point, quaternion etc, a floating point type template argument is used to accommodate required precision. If in your situation, aforementioned structures, are used to build aliases such as:

using Point = point<float>

Then the solution is simple, you wrap them in following way:

    py::class_<Point>(m, "Point")
            .def(py::init<>())
            .def_property("x", [](const Point& o){ return o._x; }, [](Point& o, float v){ o._x = v;});

Situation gets more complicated when in the C++ code, point<float>, point<double> etc appear. Those are two different types, and they'd have to be wrapped independently:

template <typename T>
struct point{
    T _x, _y, _z;
};

template<typename T>
void wrap_point(const char* type_name, py::module& m)
{
    py::class_<point<T>>(m, type_name)
            .def(py::init<>())
            .def_property("x", [](const point<T>& o){ return o._x; }, [](point<T>& o, T v){ o._x = v;});
}

PYBIND11_MODULE(example, m) {
    wrap_point<float>("pointf", m);
    wrap_point<double>("pointd", m);
}

Your question about the usage of shared_ptr is unfortunately too vague, you have to be more specific and give more context.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.