2

I have this simple wrapper working and I am trying to make changes in order to get the array all at once to use it in python.

test.cpp

#include <iostream>
using namespace std;

class Test{

    public:

    int ret(void);

};

int vec[10] = {0,1,2,3,4,5,6,7,8,9};

int Test::ret(){

    return *vec; // This obviously won't work

}

extern "C" {

    Test* Test_new(){ return new Test();}
    int Test_ret(Test* test){ return test->ret();}
}

test.py

from ctypes import cdll
lib = cdll.LoadLibrary('./libtest.so')

class Test(object):
    def __init__(self):
        self.obj = lib.Test_new()

    def ret(self):
        return lib.Test_ret(self.obj)

dev = Test()
ret = dev.ret()
print ("Return", ret)

Compiling script

g++ -c -fPIC test.cpp -o test.o
g++ -shared -Wl,-soname,libtest.so -o libtest.so  test.o

How can I do it?

  • You can use Cython or Pybind11 or maybe SWIG to wrap a C-style array in a numpy array. – evamicur May 08 '18 at 15:02
  • *ctypes* stands for **C** types, meaning that it can only handle *C* types. You want to pass *C++* types. Either wrap your *C++* methods in *C* functions, either crate a *Python* dynamic module. You could takea look at https://stackoverflow.com/questions/47276327/pass-str-as-an-int-array-to-a-python-c-extended-function-extended-using-swig/47296602#47296602 for more details. – CristiFati May 08 '18 at 15:06

0 Answers0