如何将数组从C ++传递给Python?

时间:2018-05-08 14:52:00

标签: python c++ arrays wrapper

我有这个简单的包装工作,我正在尝试按顺序进行更改 一次获取数组以在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)

编译脚本

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

我该怎么做?

0 个答案:

没有答案