我试图在C中使用python包装器来处理数组排序函数.C接受数组,将整数按最小值排序到最大值,然后返回数组。但是当我运行它时,我得到错误:
Traceback (most recent call last):
File "sortarray.py", line 25, in <module>
newarray = sortArray(array)
File "sortarray.py", line 8, in sortArray
libsortarray.sortArray.argtypes = (ctypes.c_int, ctypes.POINTER(ctypes.c_int))
File "/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 378, in __getattr__
func = self.__getitem__(name)
File "/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py", line 383, in __getitem__
func = self._FuncPtr((name_or_ordinal, self))
AttributeError: dlsym(0x7f84484280e0, sortArray): symbol not found
的Python:
import ctypes
libsortarray = ctypes.CDLL('libsortarray.so')
def sortArray(array):
global libsortarray
libsortarray.sortArray.argtypes = (ctypes.c_int, ctypes.POINTER(ctypes.c_int))
arraySize = len(array)
array_type = ctypes.c_int * arraySize
result = libsortarray.sortArray(ctypes.c_int(arraySize), array_type(*array))
return result
file = open('bigarray.txt', 'r')
#Bigarray.txt is just 10,000 lines each with a single integer
array = []
arraySize = 10000
for i in range(0,arraySize):
array.append(int(file.readline()))
file.close()
newarray = sortArray(array)
print newarray
libsortarray函数
int* sortArray(int, int*);
int* sortArray(int arraySize, int* array) {
int temp, i, j;
for (i=0; i<arraySize; i++)
for (j=i+1; j<arraySize; j++)
if (array[i] > array[j]) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
答案 0 :(得分:3)
如果源是C ++,则需要将该函数声明为extern "C" int *sortArray(int, int *)
。此外,当函数返回指针时,将restype
属性设置为指针类型,在本例中为sortArray.restype = POINTER(c_int)
。否则,在64位进程中,地址会被截断为32位,从而产生一个错误的指针,在访问时可能会出现段错误。此外,这更像是一种风格问题,声明global libsortarray
并手动换行arraySize
为c_int(arraySize)
都是不必要的混乱。
也就是说,库函数对数组进行了排序,因此没有理由返回任何内容,即只返回类型void
。这是一个实现此建议修改的示例。
<强> sortarray.cpp:强>
extern "C" void sortArray(int, int *);
void sortArray(int arraySize, int *array)
{
int temp, i, j;
for (i = 0; i < arraySize; i++)
for (j = i + 1; j < arraySize; j++)
if (array[i] > array[j]) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
// g++ -shared -fPIC -o libsortarray.so sortarray.cpp
<强> sortarray.py 强>
import ctypes
libsortarray = ctypes.CDLL('./libsortarray.so')
libsortarray.sortArray.restype = None
libsortarray.sortArray.argtypes = (ctypes.c_int,
ctypes.POINTER(ctypes.c_int))
def sort_array(array):
"""Return a sorted copy of the input array or sequence."""
array_size = len(array)
array = (ctypes.c_int * array_size)(*array)
libsortarray.sortArray(array_size, array)
return array
if __name__ == '__main__':
seq = [7, 0, 8, 4, 3, 6, 9, 1, 5, 2]
print 'Unsorted Array:\n', seq
print 'Sorted Array:\n', sort_array(seq)[:]
<强>输出:强>
Unsorted Array:
[7, 0, 8, 4, 3, 6, 9, 1, 5, 2]
Sorted Array:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]