2016-07-13 13 views
1

Cythonを使用してC++ライブラリのラッパーを作成しようとしています。しかし、ライブラリの関数の1つがパラメータconst char**を取りますので、私は今問題に取り組んでいます。どうやら、私は文字列のリストを渡しているので、私はジレンマに私を残して、この変換を行うことができません(Why am I getting an error converting a ‘float**’ to ‘const float**’?)、それはx関数に呼び出す、私は対応するchar **オブジェクトを生成しようとしています、のループのためのmallocと使用して、aそれを呼びましょう:Cythonのchar **をconst char **に変換する方法は?

def f(x): 
cdef char** a = <char**> malloc(len(x) * sizeof(char*)) 
for index, item in enumerate(x): 
    a[index] = item 
...... 

は、ここでは回避策はありますか?私が考えることができるのはconst_castですが、Cythonで実装されているかどうかはわかりません。

答えて

2

次のコードは、cPython V20.0でコンパイルされます。それはあなたの問題を解決しますか?

# distutils: language = c++ 

from libc.stdlib cimport malloc 

def f(x): 
    cdef const char** a = <const char**> malloc(len(x) * sizeof(char*)) 
    for index, item in x: 
     a[index] = item 
+1

、ありがとう! – Alex

+0

リスト 'x'がどこかで参照されている限り、これは機能します。その後、配列は、割り当てが解除され、おそらく再利用されたメモリ位置を指し示します。また、 'x'の内容を変更すると、問題が発生する可能性があります。 –

0

あり、この古いanswerですが、私は違っto_cstring_array少しを実装します(strdupの使用を、無PyString_AsString)それがなかった

from libc.stdlib cimport malloc, free 
from libc.string cimport strdup 

cdef char ** to_cstring_array(list strings): 
    cdef const char * s 
    cdef size_t l = len(strings) 

    cdef char ** ret = <char **>malloc(l* sizeof(char *)) 
    # for NULL terminated array 
    # cdef char ** ret = <char **>malloc((l + 1) * sizeof(char *)) 
    # ret[l] = NULL 

    for i in range(l): 
     s = strings[i] 
     ret[i] = strdup(s) 
    return ret 
関連する問題