[英]Type casting python int to long in scipy.weave.inline
Given the following code: 给出以下代码:
from scipy.weave import inline
code = "return_val = input_val + 1;"
inline(code, ["input_val"], local_dict=dict(input_val=-9223372036854775808))
The resulting C code internally converts the long int into int and happily returns 1. Trying to specify input_val=np.int64(-9....)
or input_val=long(-9...)
gives a compilation error, as the numpy int type is not converted at all and gets treated as a PyObject. 生成的C代码在内部将long int转换为int并愉快地返回1。尝试指定
input_val=np.int64(-9....)
或input_val=long(-9...)
会产生编译错误,因为numpy int类型根本不会转换,会被视为PyObject。 I saw some mentions of a type_converters
keyword argument for inline
, but the documentation unfortunately doesn't detail its handling further. 我看到一些提到
inline
的type_converters
关键字参数的信息,但是不幸的是文档没有详细说明其处理方式。 Any ideas, how to force type conversion to long instead of int? 有什么想法,如何强制类型转换为long而不是int?
This finally helped. 这终于有所帮助。 My compiler didn't like the inbuilt long_converter.
我的编译器不喜欢内置的long_converter。 So this overrides some type settings for long and prepends the default converter list:
因此,这会长时间覆盖某些类型设置,并在默认转换器列表之前添加:
from scipy.weave import inline, converters, c_spec
class long_converter(c_spec.scalar_converter):
def init_info(self):
c_spec.scalar_converter.init_info(self)
# !! long to int conversion isn't safe!
self.type_name = 'long'
self.check_func = 'PyLong_Check'
self.c_type = 'long'
self.return_type = 'long'
self.to_c_return = "(long) PyLong_AsLongLong(py_obj)"
self.matching_types = [types.LongType]
type_conversion = [long_converter()] + converters.default
inline("return_val = input_val + 1;", ["input_val"],
local_dict=dict(input_val=long(-9223372036854775808)),
type_converters=type_conversion)
>>> -9223372036854775807
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.