user3667089
user3667089

Reputation: 3288

Pybind 11: How to bind C++ function that has pointer arguments?

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?

Upvotes: 1

Views: 2290

Answers (1)

ChrisD
ChrisD

Reputation: 967

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.

Upvotes: 1

Related Questions