Ctypes 返回数组

ccl*_*oyd 3 c python arrays ctypes pointers

我正在尝试为 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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

和 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;
}
Run Code Online (Sandbox Code Playgroud)

Ery*_*Sun 5

如果源代码是 C++,则需要将函数声明为extern "C" int *sortArray(int, int *). 此外,当函数返回指针时,请将restype属性设置为指针类型,在本例中为sortArray.restype = POINTER(c_int). 否则,在 64 位进程中,地址会被截断为 32 位,从而创建一个错误指针,在访问时可能会出现段错误。另外,这更多的是风格问题,声明global libsortarray和手动包装arraySize都是c_int(arraySize)不必要的混乱。

也就是说,库函数对数组进行了就地排序,因此没有理由返回任何内容,即只需将返回类型设置为void。下面是实现此建议修改的示例。

排序数组.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
Run Code Online (Sandbox Code Playgroud)

排序数组.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)[:]
Run Code Online (Sandbox Code Playgroud)

输出:

Unsorted Array:
[7, 0, 8, 4, 3, 6, 9, 1, 5, 2]
Sorted Array:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Run Code Online (Sandbox Code Playgroud)