How to call c++ in-class functions (whose arguments are float pointers) in python with pybind11 #4599
-
I want to call a c++ class function (with a float pointer as argument) in python using pybind11.
The following python code called the class.
However, the following error occurred
How should I deal with this? |
Beta Was this translation helpful? Give feedback.
Answered by
Shin-ichi-Takayama
Apr 1, 2023
Replies: 1 comment
-
The solution was to define a class to WRAP as follows. #include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
namespace py = pybind11;
class MyClass {
public:
void myFunc(float *arr, int size) {
for (int i = 0; i < size; i++) {
arr[i] += 1.0f;
}
}
};
class MyClassWrapper {
private:
MyClass my_py_class;
public:
void myPyFunc(py::array_t<float> input_array, int size) {
// Get a pointer to the underlying data
float *data = static_cast<float *>(input_array.request().ptr);
my_py_class.myFunc(data, size);
}
};
PYBIND11_MODULE(example, m) {
py::class_<MyClassWrapper>(m, "MyClassWrapper")
.def(py::init<>())
.def("myPyFunc", [](MyClassWrapper& wrapper, py::array_t<float> input_array, int size){
wrapper.myPyFunc(input_array, size);
});
} The code for the caller is as follows. import numpy as np
import sys
sys.path.append( "./build" )
import example
# Create an instance of MyClass
my_obj = example.MyClassWrapper()
# Create a NumPy array
arr = np.array([1.0, 2.0, 3.0], dtype=np.float32)
# Call myFunc with the NumPy array
my_obj.myPyFunc(arr, arr.size)
# Print the updated array
print(arr) #[2. 3. 4.] |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
Shin-ichi-Takayama
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The solution was to define a class to WRAP as follows.