1

Let's suppose I am given a function that looks like this

void myFunc(int *a){
  a[0]++;
  a[1]++;
}

I tried to bind this function with the below

#include "pybind11/numpy.h"
#include "pybind11/pybind11.h"

namespace py = pybind11;

PYBIND11_MODULE(pybindtest, m) {
  m.def("myFunc", [](py::array_t<int> buffer){
    py::buffer_info info = buffer.request();
    myFunc(static_cast<int *>(info.ptr));
  });
}

and use the below python code to test

import pybindtest

a=[1,2];

pybindtest.myFunc(a);

print(a)

This shows [1, 2] instead of [2, 3]. Given that myFunc is written by other people, so I am not allowed to change the API. Is it possible to bind this function into python? If yes, what am I doing wrong?

1
  • 1
    Python integers are very different from C++'s ints, so this really shouldn't work. Commented Oct 16, 2021 at 22:20

1 Answer 1

1

Try this in your python script

import numpy as np
import pybindtest

a=np.array([1,2], dtype=np.int32);

pybindtest.myFunc(a);

print(a)

The problem is that a is a python list, not an array of ints. By default pybind11 will convert the list into a suitable array - see the section about py::array::forcecast in the docs. But in doing so it creates a copy and the increments in myFunc are performed on that.

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

2 Comments

It works! But it's pybindtest.myFunc(a); instead of pybindtest(a);
Oops thanks. Edited.

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.