如何从Python打印outdata3,outdata4值?

时间:2012-02-10 10:37:41

标签: python numpy ctypes

我想从Python代码中获取outdata3,outdata4的值。 我使用ctypes来调用c函数。 c函数如下:

#include <stdio.h>

void cfunction(int indata1, double indata2, int * outdata3, double * outdata4)
{
    int i;
    for (i = 0; i < indata1; ++i)
    {
        outdata3[i] = indata1;
        outdata4[i] = indata2;
        //printf("indata3 [%d] = %d\n", i, outdata3[i]);
        //printf("indata4 [%d] = %1.1f\n", i, outdata4[i]);     
    }
}

下面的代码是Python代码:

import numpy
import ctypes

indata1 = ctypes.c_int(8)
indata2 = ctypes.c_double(3.4)
#outdata3 = numpy.zeros((5), dtype=numpy.int)
#outdata4 = numpy.zeros((5), dtype=numpy.double)

lib = ctypes.cdll.LoadLibrary('./ctest.so')
fun = lib.cfunction

# Allocate array of int*
outdata3 = (ctypes.POINTER(ctypes.c_int) * 8)()
#for i in range(8):
#    # Allocate arrays of int
#    outdata3[i] = (ctypes.c_int * 8)()

# Allocate array of double*
outdata4 = (ctypes.POINTER(ctypes.c_double) * 8)()
#for i in range(8):
#    # Allocate arrays of double
#    outdata4[i] = (ctypes.c_double * 8)()

fun(ctypes.c_int(8), ctypes.c_double(3.4), ctypes.byref(outdata3), types.byref(outdata4))

#fun(ctypes.c_void_p(indata.ctypes.data), ctypes.c_int(5), ctypes.c_int(6),
#    ctypes.c_void_p(outdata.ctypes.data))

#print('outdata3:    ', outdata3.contents)
#print('outdata4: ', outdata4.contents)


def dump1(a,rows):
    for i in range(rows):
        print a[i]

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

dump1(outdata3, 8)
#dump1(outdata4, 8)

我可以从上面的代码中得到以下内容。

[===>19:14:48]one+two:python test.py 
<__main__.LP_c_long object at 0x93566ec>
<__main__.LP_c_long object at 0x93566ec>
<__main__.LP_c_long object at 0x93566ec>
<__main__.LP_c_long object at 0x93566ec>
<__main__.LP_c_long object at 0x93566ec>
<__main__.LP_c_long object at 0x93566ec>
<__main__.LP_c_long object at 0x93566ec>
<__main__.LP_c_long object at 0x93566ec>

但是我想要下面的值。

0.0 1.0 2.0 3.0 4.0 5.0
1.0 2.0 3.0 4.0 5.0 6.0
2.0 3.0 4.0 5.0 6.0 7.0
3.0 4.0 5.0 6.0 7.0 8.0
4.0 5.0 6.0 7.0 8.0 9.0

1 个答案:

答案 0 :(得分:0)

您将错误的类型传递给cfunction。你应该将一个int数组和一个double数组传递给cfunction。

outdata3 = (ctypes.c_int * 8)()
outdata4 = (ctypes.c_double * 8)()
fun(ctypes.c_int(8), ctypes.c_double(3.4), outdata3, outdata4)

def dump1(a,rows):
    for i in range(rows):
        print a[i]

dump1(outdata3, 8)

或者你可以将numpy数组传递给cfunction:

lib.cfunction.argtypes = [c_int, c_double, 
    np.ctypeslib.ndpointer(dtype=np.int32, ndim=1),
    np.ctypeslib.ndpointer(dtype=np.float64, ndim=1)]

outdata3 = np.zeros(8, np.int32)
outdata4 = np.zeros(8, np.float64)

lib.cfunction(8, 3.4, outdata3, outdata4)
print outdata3
print outdata4