在Cython中,如何在不使用Python对象(例如bytes
或str
)作为中间体的情况下转换生成C double的C字符串( char *
)表示?
事实上,我已经在C扩展名文件(.pyx)中定义了我的函数,如下所示:
cdef void function(self, char* var1) nogil: cdef char* chaine ="" cdef double inter = 0.0 #Here there is some treatment which modifies the value of the local variable 'inter' so that it contains a double value different from 0 strcat(chaine , "(") strcat(chaine , inter) strcat(chaine , ")**beta") strcpy(&var1, chaine)
编译完文件后,我有错误C2440 : impossible de convertir de 'double' en 'char*'
C2168 : strcat nombre de paramètres de fonction intrinséque insuffisant
C2440 : impossible de convertir de 'double' en 'char*'
和C2168 : strcat nombre de paramètres de fonction intrinséque insuffisant
我该如何解决问题?
抛开在python或C级别是否值得这样做的问题,看起来你的示例代码中出现了C级的几个关键误解。 有很多封面,所以我只会提供一些指示,以帮助引导你朝着正确的方向前进; 一旦您对C和cython感觉更舒服,可以随意发布您的代码的更正版本作为答案。
首先,关于指针的一个词。 指针只是一个保存内存地址的变量。 该存储器地址“指向”存储器中的某些内容。 这是一个简单的示例,可以清除它:
cdef int a_number = 42#just a regular int, nothing special here :) cdef int* a_pointer = &a_number#"referencing" to get the address of a_number cdef int b_number = a_pointer[0]#"dereferencing" to get the value at a_pointer #note the dereferencing syntax is different in cython than in C!!!
其次是function如何运作。 在C中,一切都是按值传递的 。 这意味着无论何时将参数传递给函数,都会生成参数的副本 ,并在此副本上执行操作。 这包括指针; 如果您尝试设置var1
指针,就像在function
中尝试一样,实际的var1
指针将保持不变,并且只修改function
范围内的本地副本。 显然不是我们想要的!
第三,我们需要看看字符串是如何用C表示的。字符串基本上是你关心的字符列表,后跟一个空终止符