2013-07-07 14 views
7

Mając podany kod hipotetyczny:Szybkie ciąg tablicą - 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 

jest jakiś sposób, jak konwertować list do C tablic?

Przeczytałem i wypróbowałem Cython - converting list of strings to char **, ale to tylko powoduje błędy.

Odpowiedz

9

Spróbuj użyć następującego kodu. to_cstring_array funkcja w poniższym kodzie jest to, co chcesz.

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']) 
+0

Cóż, to jest niesamowita odpowiedź! bardzo dziękuję za to, ale chodzi o to, że linia ret [i] = PyString_AsString (list_str [i]) podnosi otrzymywanie char * z tymczasowej wartości Pythona podczas kompilacji – Jendas

+0

Dobra, moja zła! Zapomniałem cpython.string cimport PyString_AsString. Teraz działa dobrze! Dziękuję Ci!! – Jendas