为什么 ctypes.CDLL 假设长结果类型,即使它实际上是 long long?

问题描述 投票:0回答:1

考虑下面的Python代码 - 似乎调用.dll的函数由于某种原因需要很长时间(系统是Windows x64,如果它很重要的话)。 它为什么要这么做?有办法禁用它吗?在其他情况下,例如,它会妨碍吗?如果我要传递

long long
参数或使用
long long
s 初始化结构?

import ctypes

hello_lib = ctypes.CDLL("./hello.dll")

n = 13
# returns 1932053504 instead of 6227020800
print(hello_lib.factorial(n))

# for some reason result type is long,
# though it's declared as long long in .dll
# <class 'ctypes.c_long'>
print(hello_lib.factorial.restype)

hello_lib.factorial.restype = ctypes.c_longlong
# return 6227020800, changing result type helped
print(hello_lib.factorial(n))

.dll代码:

// choco install mingw
// gcc -shared -o hello.dll hello.c

#include <stdio.h>

long long int factorial(int n) {
    if (n>=1) {
        return n*factorial(n-1);
    }
    return 1;
}

python dll ctypes
1个回答
0
投票

ctypes
不知道返回类型是什么。 DLL 只知道 C 函数的名称和入口点,而不知道参数或返回类型。
c_int
(在大小相同的操作系统上别名为
c_long
)只是默认值。

用户有责任相应地设置

.argtypes
.restype

© www.soinside.com 2019 - 2024. All rights reserved.