【问题标题】:How do you speficy the type of variable from python to C in Ctypes?如何在 Ctypes 中指定从 python 到 C 的变量类型?
【发布时间】:2020-10-21 13:40:44
【问题描述】:

目前我正在学习 C 类型。我有一段 C 代码。这不是整个代码,但我认为其余的与分享无关。 sin 和 cos 函数在上面的原始代码中定义。

C:

double tan(f) double f;
{
       return sin(f)/cos(f); 

Python:

import ctypes

testlib = ctypes.CDLL('./testlib.so')

testlib.tan.argtypes = ctypes.c_double
teslib.tan.restype = ctypes.c_double

print(testlib.tan(2))

首先我没有使用这些行:

testlib.tan.argtypes = ctypes.c_double
teslib.tan.restype = ctypes.c_double

我得到了一个输出,但输出为 0。我认为 double 值被向下转换为 int。

我想要实现的是我从 python 向 C 发送一个 double,C 会返回一个 double。

我已经熟悉这个文档,但我没有找到正确的答案: https://docs.python.org/3/library/ctypes.html

问题:我应该如何修改我的代码以获得良好的输出?

【问题讨论】:

    标签: python c ctypes


    【解决方案1】:

    因为 argtypes 必须是类型序列,所以使用例如testlib.tan.argtypes = ctypes.c_double, - 请注意此处的尾随 ,

    补充说明

    • 具有单独声明的参数类型的 K&R 函数定义已过时,因此请使用 double tan(double f) 代替 double tan(double f)

    • tan 是来自 C 标准库的三角函数,所以最好使用不同的名称

    所以它可能看起来像:

    #include <math.h>
    
    double tan1(double f) {
        return sin(f)/cos(f);
    }
    

    不要忘记在 Python 端也使用名称 tan1

    testlib.tan1.argtypes = ctypes.c_double,
    testlib.tan1.restype = ctypes.c_double
    
    print(testlib.tan1(2))
    

    结果是:

    -2.185039863261519
    

    【讨论】:

    • 非常感谢!用 Ctypes 传递一个值是掌握 C 类型原理的实践。我实际上需要处理整个 numpy 数组。但我觉得这真的很难,因为在网上找不到真正的 1:1 示例。我发布了一个新主题:stackoverflow.com/questions/64478880/…。如果你有时间,请你给我反馈一下如何实现这个目标? @StephanSchlecht
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    • 2010-09-28
    相关资源
    最近更新 更多