简体   繁体   中英

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. I saw some mentions of a type_converters keyword argument for inline , but the documentation unfortunately doesn't detail its handling further. Any ideas, how to force type conversion to long instead of int?

This finally helped. My compiler didn't like the inbuilt 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM