1.把一个二维数组转化成一维的,传入C
void show_matrix(int *matrix, int rows, int columns)
{
int i, j;
for (i=0; i
编译成动态库供python调用 ,gcc
-
shared
-
O2 mystuff.c
-
ldl
-
o mystuff.so
import ctypes
import numpy as np
lib = ctypes.cdll.LoadLibrary("./mystuff.so")
arr = np.zeros((3,5))
#arr = np.array([[1,2],[3,4]])
tmp = np.asarray(arr)
rows, cols = tmp.shape
dataptr = tmp.ctypes.data_as(ctypes.c_char_p)
lib.show_matrix(dataptr, rows, cols)
运行 python test.py
2把numpy的二维数组打包成ctypes的标准数组形式,传送给C。
from ctypes import *
import numpy
def Convert1DToCArray(TYPE, ary):
arow = TYPE(*ary.tolist())
return arow
def Convert2DToCArray(ary):
ROW = c_int * len(ary[0])
rows = []
for i in range(len(ary)):
rows.append(Convert1DToCArray(ROW, ary[i]))
MATRIX = ROW * len(ary)
return MATRIX(*rows)
a=numpy.array([[1,2,2],[1,3,4]])
caa = Convert2DToCArray(a)
def ShowCArrayArray(caa):
for row in caa:
for col in row:
print col
ShowCArrayArray(caa)
3 如果将python中list传入C函数数组,则需要提前转换。
import ctypes
pyarray = [1, 2, 3, 4, 5]
carray = (ctypes.c_int * len(pyarray))(*pyarray) //有点类似malloc的方式生成carray
print so.sum_array(carray, len(pyarray))
pyarray = [1,2,3,4,5,6,7,8]
carray = (ctypes.c_int*len(pyarray))(*pyarray)
so.modify_array(carray, len(pyarray))
print np.array(carray)
output
[10 20 30 40 50 60 70 80]
import ctypes
import numpy as np
from numpy.ctypeslib import ndpointer
so = ctypes.CDLL('./sum.so')
pyarray = np.array([1,2,3,4,5,6,7,8], dtype="int32")
fun = so.modify_array
fun.argtypes = [ndpointer(ctypes.c_int), ctypes.c_int]
fun.restype = None
fun(pyarray, len(pyarray))
print np.array(pyarray)
注意:numpy中的数据类型指定很重要,即dtype的设定