如何在Cython中使用128位整数 [英] How to use 128 bit integers in Cython
问题描述
在我的64位计算机上, long long
类型具有64位.
On my 64 bit computer the long long
type has 64 bits.
print(sizeof(long long))
# prints 8
我需要使用128位整数,幸运的是 GCC支持这些.如何在Cython中使用它们?
I need to use 128 bit integers and luckily GCC supports these. How can I use these within Cython?
以下内容无效.编译仅包含
The following doesn't work. Compiling foo.pyx
containing just
cdef __int128_t x = 0
收益
$ cython foo.pyx
Error compiling Cython file:
------------------------------------------------------------
...
cdef __int128_t x = 0
^
------------------------------------------------------------
foo.pyx:2:5: '__int128_t' is not a type identifier
推荐答案
这不再是解决方法,这是正确的方法.另请参阅@IanH的答案.
this is NOT a workaround anymore, this is the right way to do it. Refer also to @IanH's answer.
现在,您遇到的问题是 cython
无法识别您的类型,而 gcc
可以识别您的类型.因此,我们可以尝试欺骗
Now, the problem you have is that cython
does not recognize your type, while gcc
does. So we can try to trick cython
.
文件 helloworld.pyx
:
cdef extern from "header_int128.h":
# this is WRONG, as this would be a int64. it is here
# just to let cython pass the first step, which is generating
# the .c file.
ctypedef unsigned long long int128
print "hello world"
cpdef int foo():
cdef int128 foo = 4
return 32
文件 header_int128.h
:
typedef __int128_t int128;
文件 setup.py
:
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules = cythonize("helloworld.pyx"))
现在,在我的机器上,当我运行 python setup.py build_ext --inplace
时,第一步通过了,并生成了 helloworld.c
文件,并且然后 gcc
编译也会通过.
Now, on my machine, when I run python setup.py build_ext --inplace
, the first step passes, and the file helloworld.c
is generated, and then the gcc
compilation passes as well.
现在,如果打开文件 helloworld.c
,则可以检查变量 foo
实际上是否声明为 int128
.
Now if you open the file helloworld.c
, you can check that your variable foo
is actually declared as an int128
.
使用此替代方法要非常小心.特别是,例如,如果您将 int128
分配给 int64
,则cython不需要强制转换C代码,因为在该过程的该步骤实际上并没有区分它们.
Be very careful with using this workaround. In particular, it can happen that cython will not require a cast in the C code if you assign an int128
to a int64
for example, because at that step of the process it actually does not distinguish between them.
这篇关于如何在Cython中使用128位整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!