2012-01-09 172 views
6

我可以像下面那樣將一維數組傳遞給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 
+0

這是我一直教一劈,但爲什麼不只是傳遞指針只要整數? – 2012-01-09 03:58:54

+0

因爲類型可以是double .. etc不只是整數。 – wonjun 2012-01-09 17:14:39

+0

指針總是可以用長整型表示。然後回到你想要的任何類型。 – 2012-01-16 15:30:24

回答

6

這裏有一個方法。我沒有看到用double **使用numpy的好方法。

TEST.CPP(Windows)中

#include <stdio.h> 

extern "C" __declspec(dllexport) void cfun(const double ** indata, int rowcount, int colcount, double ** outdata) { 
    for (int i = 0; i < rowcount; ++i) { 
     for (int j = 0; j < colcount; ++j) { 
      outdata[i][j] = indata[i][j] * 4; 
     } 
    } 
} 

test.py

import numpy 
import ctypes 

# Allocate array of double* 
indata = (ctypes.POINTER(ctypes.c_double) * 5)() 
for i in range(5): 
    # Allocate arrays of double 
    indata[i] = (ctypes.c_double * 6)() 
    for j in range(6): 
     indata[i][j] = 1.0 

outdata = (ctypes.POINTER(ctypes.c_double) * 5)() 
for i in range(5): 
    outdata[i] = (ctypes.c_double * 6)() 
    for j in range(6): 
     outdata[i][j] = 1.0 

lib = ctypes.cdll.LoadLibrary('test') 
fun = lib.cfun 

def dump(a,rows,cols): 
    for i in range(rows): 
     for j in range(cols): 
      print a[i][j], 
     print 

dump(indata,5,6) 
fun(ctypes.byref(indata),5,6,ctypes.byref(outdata)) 
dump(outdata,5,6) 

輸出

1.0 1.0 1.0 1.0 1.0 1.0 
1.0 1.0 1.0 1.0 1.0 1.0 
1.0 1.0 1.0 1.0 1.0 1.0 
1.0 1.0 1.0 1.0 1.0 1.0 
1.0 1.0 1.0 1.0 1.0 1.0 
4.0 4.0 4.0 4.0 4.0 4.0 
4.0 4.0 4.0 4.0 4.0 4.0 
4.0 4.0 4.0 4.0 4.0 4.0 
4.0 4.0 4.0 4.0 4.0 4.0 
4.0 4.0 4.0 4.0 4.0 4.0 
+0

我在創建「.so」文件時遇到錯誤 test.cpp:4:1:錯誤:期望的構造函數,析構函數或類型轉換之前'('token – wonjun 2012-01-09 05:22:23

+0

我在linux上,所以這段代碼不工作 – wonjun 2012-01-09 05:27:07

+0

它的工作原理沒有「__declspec(dllexport)」感謝和在fortran中,多維數組可以直接與numpy直接傳遞嗎?fwrap ..實際上我正在尋找傳遞數組python <-> c,C++ <-> fortran。 – wonjun 2012-01-09 05:51:41