0

目前我正在学习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 发送一个双精度数,C 将返回一个双精度数。

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

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

4

1 回答 1

0

由于 argtypes 必须是类型序列,请使用 eg - 注意此处testlib.tan.argtypes = ctypes.c_double,的尾随,

附加说明

  • 单独声明参数类型的 K&R 函数定义已过时,因此不要double tan(f) double f;使用double tan(double f)

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

所以它可能看起来像:

#include <math.h>

double tan1(double f) {
    return sin(f)/cos(f);
}

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

testlib.tan1.argtypes = ctypes.c_double,
testlib.tan1.restype = ctypes.c_double

print(testlib.tan1(2))

结果是:

-2.185039863261519
于 2020-10-21T18:35:13.900 回答