我可以像下面那樣將一維數組傳遞給python。 我不知道我是否可以通過使用ctypes,numpy將C++雙指針數組傳遞給python。將C++雙指針傳遞給python
TEST.CPP:
#include <stdio.h>
extern "C" void cfun(const void * indatav, int rowcount, int colcount, void * outdatav);
void cfun(const void * indatav, int rowcount, int colcount, void * outdatav) {
//void cfun(const double * indata, int rowcount, int colcount, double * outdata) {
const double * indata = (double *) indatav;
double * outdata = (double *) outdatav;
int i;
puts("Here we go!");
for (i = 0; i < rowcount * colcount; ++i) {
outdata[i] = indata[i] * 4;
}
puts("Done!");
}
test.py:
import numpy
import ctypes
indata = numpy.ones((5,6), dtype=numpy.double)
outdata = numpy.zeros((5,6), dtype=numpy.double)
lib = ctypes.cdll.LoadLibrary('./ctest.so')
fun = lib.cfun
# Here comes the fool part.
#fun(ctypes.c_void_p(indata.ctypes.data), ctypes.c_void_p(outdata.ctypes.data))
fun(ctypes.c_void_p(indata.ctypes.data), ctypes.c_int(5), ctypes.c_int(6),
ctypes.c_void_p(outdata.ctypes.data))
print 'indata: %s' % indata
print 'outdata: %s' % outdata
這是我一直教一劈,但爲什麼不只是傳遞指針只要整數? – 2012-01-09 03:58:54
因爲類型可以是double .. etc不只是整數。 – wonjun 2012-01-09 17:14:39
指針總是可以用長整型表示。然後回到你想要的任何類型。 – 2012-01-16 15:30:24