%%cython
import cython
cdef int k = 65
cdef unsigned char kk = cython.cast("char", k)
print kk
结果是65.我已经尝试<char>
将65转换为'A'
任何人都有一些想法?我目前在Ipython笔记本上工作。
提前谢谢!!
将帖子 我添加了这个问题的第一个动机。
在c中,
int i = 65;
char c = i;
printf("%c", c); //prints 'A'
因为char'A'已经是int,如果我正确理解
但是在Cython中,
%%cython
import cython
cdef int k = 65
cdef char kk = cython.cast("char", k)
print <char>kk, <int>kk
同样的结果。
答案 0 :(得分:2)
Python没有真正的字符类型。 Python有字符串。 ord()
函数的工作原理是将1个字符的字符串作为函数参数,如果字符串的长度较长,则会抛出错误。
在幕后,所有ord()
确实只是将char
强制转换为int
。在C中,我可以写一个像这样的天真函数:
#include <string.h> // for strlen
int c_ord(const char* string)
{
// declare our variables
size_t length;
int ret;
// check the length
// note that Python actually stores the length,
// so this wouldn't be done in real code.
// This is here for example
length = strlen(string);
if (length != 1) {
// invalid length, set a dummy placeholder
ret = -1;
} else {
// just grab our value
ret = string[0];
}
return ret;
}
注意所有ord()
正在做的是获取确切的值,只获取字符,而不是字符串表示。 Cython正在做的是真正的行为:将char视为整数并因此打印出它的整数值。为了处理像字符串这样的字符,我们可以创建一个字符数组,让Python知道它是一个字符串。内置方法chr
为我们所有人做了这件事。
%%cython
import cython
cdef int k = 65
print chr(k)
要在Cython中编写一个简单的方法来创建一个以null结尾的C字符串,并可选择将其转换为Python字符串,我们可以执行以下操作:
Python没有真正的字符类型。 Python有字符串。 ord()
函数的工作原理是将1个字符的字符串作为函数参数,如果字符串的长度较长,则会抛出错误。
在幕后,所有ord()
确实只是将char
强制转换为int
。在C中,我可以写一个像这样的天真函数:
#include <string.h> // for strlen
int c_ord(const char* string)
{
// declare our variables
size_t length;
int ret;
// check the length
// note that Python actually stores the length,
// so this wouldn't be done in real code.
// This is here for example
length = strlen(string);
if (length > 1) {
// invalid length, set a dummy placeholder
ret = -1;
} else {
// just grab our value
ret = string[0];
}
return ret;
}
注意所有ord()
正在做的是获取确切的值,只获取字符,而不是字符串表示。 Cython正在做的是真正的行为:将char视为整数并因此打印出它的整数值。为了处理像字符串这样的字符,我们可以创建一个字符数组,让Python知道它是一个字符串。内置方法chr
为我们所有人做了这件事。
%%cython
import cython
cdef int k = 65
print chr(k)
要编写一个简单的扩展来执行chr()
并创建一个以空字符结尾的字符串(通常称为C字符串),我们可以编写以下内容。
%%cython
# imports
import cython
from libc.stdlib cimport malloc, free
# create null-terminated string, or a C-string
cdef char* c_string = <char*>malloc(2) # only need 2
c_string[0] = 65 # 'A'
c_string[1] = 0 # '\0', null-termination
# ... do what we want with the C-string
# convert to Python object
cdef bytes str = c_string
# remember to free the allocate memory
free(c_string)
# use Python object
print(str)