我在python中使用ctypes模块在C中编写库,然后从python访问它。这是我的C代码:
#import <math.h>
#include <stdio.h>
void convolution(int *array, int length) {
int i;
int p = 0;
for(i=0;i<length;i++){
array[i] += 1;
}
}
这是我的python代码:
import ctypes
import numpy
import locate_file
working_directory = locate_file.locate_file()
_convolution_ = ctypes.cdll.LoadLibrary(working_directory +'libconvolution.so')
class image_type() :
def from_param(self,param) :
typename = type(param).__name__
if hasattr(self,'from_'+typename) :
return getattr(self,'from_'+typename)(param)
else :
raise TypeError('type %s not supported' %typename)
def from_list(self,param) :
c_array = numpy.ascontiguousarray(param,dtype=int)
pointer = c_array.ctypes.data_as(ctypes.c_void_p)
def from_tuple(self,param) :
return self.from_list(param)
def from_ndarray(self,param) :
return self.from_list(param)
image_type_ = image_type()
_convolution_.convolution.argtypes = [image_type_,ctypes.c_int]
_convolution_.convolution.restype = ctypes.c_void_p
def convolution(array) :
_convolution_.convolution(array,ctypes.c_int(len(array)))
return None
m = [1,2,3,4,5]
convolution(m)
问题是每次运行这个python代码时,我的python崩溃了。我知道没有在ctypes中初始化函数的argtypes和restypes会导致python崩溃,但我相信我已经把它弄错了。我哪里错了?