【问题标题】:unexpected integer returned from a C function by calling it using ctypes通过使用 ctypes 调用从 C 函数返回的意外整数
【发布时间】:2021-02-26 21:30:54
【问题描述】:

我写了以下 C 函数:

unsigned long long int myfunction(unsigned long long int number)
{
    return number;
}

创建共享库后,我想从 python 调用它:

from pathlib import Path
from ctypes import CDLL, c_ulonglong

cwd = Path.cwd()
so_file = Path.joinpath(cwd, Path("mylib.so"))
c_lib = CDLL(so_file)
c_func = c_lib.myfunction

if __name__ == '__main__':
    my_number = 844952973115541
    my_c_number = c_ulonglong(my_number)
    ans = c_ulonglong(c_func(my_c_number))
    print(ans.value)

我希望取回我给的号码,但以下号码返回:

18446744073471557781

【问题讨论】:

    标签: python c shared-libraries ctypes unsigned-long-long-int


    【解决方案1】:

    他们的 python 代码假定 c 函数返回一个 int。您可以通过添加来修复它:

    c_func.restype = c_ulonglong
    

    【讨论】:

    • @dAriush 还有c_func.argtypes = c_ulonglong,,那么您可以拨打ans = c_func(my_number)。不设置restype/argtypes 是人们对ctypes 有问题的第一大原因。
    • @mark-tolonen 感谢您提供的信息。如果我的函数接受多个参数,我应该将 argtypes 属性设置为一组类型吗?
    • @dAriush 是的,就像文档说的一样?
    猜你喜欢
    • 2020-02-24
    • 2016-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多