我正在尝试为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;
}
for i in newarray
时,它会返回一些随机整数和我认为是内存地址。如果我使用for i in range
和newarray[i]
就可以正常工作,但是否有办法仍然使用这种返回类型的for in
循环呢? - cclloydnewarray=reverseArray(arraySize,newarray)
- cclloyd