首页 > 解决方案 > 使用 Swig 从 Python long int 转换为 unsigned int 64

问题描述

我正在使用 Swig 开发一个 Python 库。我有一个类似于以下的类型图:

%typemap(in) (unsigned long long myLongParam){
   $1 = PyInt_AsUnsignedLongLongMask($input);
}

我这样调用目标 Python 函数:

#Calling with a very large integer
myFunc(0xFFFFFFFF11111111L)

这应该是一个 64 位长的无符号整数。但是,该值似乎被截断了 32 位。

标签: pythonswig

解决方案


解决了。问题不存在。问题出在其他地方,与上述代码无关。我正在执行以下错误代码:

%apply int* OUTPUT {Uint64*}

这告诉 swig 将 Uint64 视为与 int 相同,因此结果被截断。它使用 SWIG_From_int 到结果值。

我的解决方案是:

/*Uint64* parameter as reference */
%typemap(in, numinputs=0) Uint64* (Uint64 temp) {
    temp = 0;
    $1 = &temp;
}

/*Uint64* as function return typemap*/
%typemap(argout) Uint64* {
    %append_output( PyInt_FromLong( *$1 ) );
}

推荐阅读