[英]Fast string array - Cython
有以下假設代碼:
cdef extern from "string.h":
int strcmp(char* str1, char* str2)
def foo(list_str1, list_str2):
cdef unsigned int i, j
c_arr1 = ??
c_arr2 = ??
for i in xrange(len(list_str1)):
for j in xrange(len(list_str2)):
if not strcmp(c_arr1[i], c_arr2[j]):
do some funny stuff
有沒有辦法將列表轉換為c數組?
我已經閱讀並嘗試過Cython - 將字符串列表轉換為char **,但這只會引發錯誤。
請嘗試以下代碼。 to_cstring_array
函數在下面的代碼中就是你想要的。
from libc.stdlib cimport malloc, free
from libc.string cimport strcmp
from cpython.string cimport PyString_AsString
cdef char ** to_cstring_array(list_str):
cdef char **ret = <char **>malloc(len(list_str) * sizeof(char *))
for i in xrange(len(list_str)):
ret[i] = PyString_AsString(list_str[i])
return ret
def foo(list_str1, list_str2):
cdef unsigned int i, j
cdef char **c_arr1 = to_cstring_array(list_str1)
cdef char **c_arr2 = to_cstring_array(list_str2)
for i in xrange(len(list_str1)):
for j in xrange(len(list_str2)):
if i != j and strcmp(c_arr1[i], c_arr2[j]) == 0:
print i, j, list_str1[i]
free(c_arr1)
free(c_arr2)
foo(['hello', 'python', 'world'], ['python', 'rules'])
如果你使用的是Python 3,這里是對@fattru的答案的更新(在Python 2上未經測試)。
cdef extern from "Python.h":
char* PyUnicode_AsUTF8(object unicode)
from libc.stdlib cimport malloc, free
from libc.string cimport strcmp
cdef char ** to_cstring_array(list_str):
cdef char **ret = <char **>malloc(len(list_str) * sizeof(char *))
for i in xrange(len(list_str)):
ret[i] = PyUnicode_AsUTF8(list_str[i])
return ret
def foo(list_str1, list_str2):
cdef unsigned int i, j
cdef char **c_arr1 = to_cstring_array(list_str1)
cdef char **c_arr2 = to_cstring_array(list_str2)
for i in range(len(list_str1)):
for j in range(len(list_str2)):
if i != j and strcmp(c_arr1[i], c_arr2[j]) == 0:
print(i, j, list_str1[i])
free(c_arr1)
free(c_arr2)
foo(['hello', 'python', 'world'], ['python', 'rules'])
警告: PyUnicode_AsUTF8
返回的指針緩存在父unicode-object中。 這有兩個后果:
PyUnicode_AsUTF8
的調用者不負責釋放內存。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.