繁体   English   中英

从 Python 通过 ctypes 调用的 C function 返回不正确的值

[英]C function called from Python via ctypes returns incorrect value

我在 C 中编写了一个简单的 function ,它将给定的数字提高到给定的功率。 当我在 C 中调用它时,function 返回正确的值,但是当我在 Python 中调用它时,它返回一个不同的、不正确的值。

我使用以下命令创建了共享文件: $ gcc -fPIC -shared -o test.so test.c

我尝试了 C function 的不同配置,其中一些返回预期值,而另一些则没有。 例如,当我的 function 使用return x*x一个简单的正方形时,没有for循环,它在 Python 中返回了正确的值。

我希望最终能够在 python 中调用 C function ,它将返回一个二维 Z0D6178370CAD1D4E12F 数组。

#include <stdio.h>

float power(float x, int exponent)
{
    float val = x;
    for(int i=1; i<exponent; i++){
        val = val*x;
    }
    return val;
}
from ctypes import *

so_file = '/Users/.../test.so'
functions = CDLL(so_file)

functions.power.argtype = [c_float, c_int]
functions.power.restype = c_float

print(functions.power(5,3))

I obtain the expected output of 125.0 when I call the function in C, but when I call the function in python, it returns a value of 0.0.

这是我第一次使用 ctypes。 我是否犯了一个明显的错误导致 function 计算错误?

清单[Python 3.Docs]:ctypes - 用于 Python 的外部 function 库

In order for everything to be properly converted ( Python <=> C ) when calling the function (residing in a .dll ( .so )), 2 things need to be specified (leaving x86 calling convention ( Win ) aside):

  1. 参数类型
  2. 返回类型

CTypes中,这是通过指定:

  1. argtypes - 包含每个参数( CTypes )类型的列表(实际上是一个序列)(按照它们出现在 function 标头中的顺序)
  2. restype - 单个CTypes类型

旁注:上述方法的替代方法是对外部函数进行原型设计( CFUNCTYPEWINFUNCTYPEPYFUNCTYPE - 检查Function 原型部分(在开头的URL中))。


反正:

  • 未能指定
  • 拼写错误(基本上与上一个项目符号相同)

它们中的任何一个(如果需要(1) )将导致应用默认值:所有都被视为( C89风格) int s,它(在大多数系统上)32位长。
这会产生未定义的行为(2) (在错误指定它们时也适用),尤其是在64 位CPU / OS上,其中较大类型的值(例如指针)可能会被截断
显示的错误可能很多,有时会产生误导。

您拼错了argtype (末尾缺少s )。

纠正一下,你应该没问题

示例

对于由libdll.dll ( libdll.so ) 导出的 function函数,具有以下 header:

double func(uint32_t ui, float f, long long vll[8], void *pv, char *pc);

Python等效项为:

func = libdll.func
func.argtypes = (ctypes.c_uint32, ctypes.c_float, ctypes.c_longlong * 8, ctypes.c_void_p, ctypes.POINTER(ctypes.c_char))
'''
It would be a lot easier (nicer, and in most cases recommended)
  the last element to be ctypes.c_char_p,
  but I chose this form to illustrate pointers in general.
'''
func.restype = ctypes.c_double

相同(或非常相似)场景的一些(更具破坏性)结果(还有很多其他):


脚注

  • #1 :从技术上讲,有些情况不需要指定它们。 但即便如此,最好指定它们以消除任何可能的混淆:

    • Function 没有 arguments:

       function_from_dll.argtypes = ()
    • Function 返回void

       function_from_dll.restype = None
  • #2 : Undefined Behavior ( [Wikipedia]: Undefined behavior ) 顾名思义,是一段代码的结果无法“预测”(或保证)的情况。 主要案例:

    • 按预期工作
    • 没有按预期工作
      • 有一些有趣的输出/副作用
      • 崩溃


    它的“美”在于有时它看起来完全随机,有时它在某些特定情况下(不同的机器、不同的操作系统、不同的环境......)“只复制”。 归根结底,所有这些纯属巧合! 问题在于代码(可能是当前代码(最高机会)或它使用的其他代码(库、编译器))。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM