我是靠谱客的博主 有魅力橘子,这篇文章主要介绍Python 使用ctypes调用 C 函数,现在分享给大家,希望可以做个参考。

文章目录

    • 1. 文件结构
    • 2. 代码
    • 3. 分析

1. 文件结构

在这里插入图片描述

2. 代码

  1. get_angle.c

    复制代码
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    #include <stdio.h> #include <math.h> #define pi (2*acos(0.0)) float get_angle(float x, float y){ printf("you input %f and %fn", x, y); float angle = 123; if(y == 0){ if(x < 0) angle = 180; else angle = 0; } if(x == 0){ if(y > 0) angle = 90; else angle = 270; } else{ float tan_yx = fabs(y)/fabs(x); if (y > 0 && x < 0){ angle = 180 - atan(tan_yx)*180/pi; //90-180 }else if(y > 0 && x > 0){ angle = atan(tan_yx)*180 / pi; //0-90 }else if (y < 0 && x < 0){ angle = 180 + atan(tan_yx)*180/pi; //180-270 }else if (y < 0 && x > 0){ angle = 360- atan(tan_yx)*180/pi; //270-360 } } return angle; } //如果cpp文件需要添加以下代码: // 需要将上边的函数名修改为_get_angle //extern "C" //{ // void get_angle(float x, float y){ // _get_angle(x, y); // } //}
  2. 编译so文件

    C:

    复制代码
    1
    2
    gcc -o get_angle.so -shared -fPIC get_angle.c

    c++

    复制代码
    1
    2
    g++ -o get_angle.so -shared -fPIC get_angle.cpp
  3. test.py

    复制代码
    1
    2
    3
    4
    5
    6
    7
    from ctypes import * lib = cdll.LoadLibrary("./get_angle.so") lib.get_angle.restype = c_float lib.get_angle.argtypes = (c_float, c_float) a = lib.get_angle(48.0, 10.0) print(a)

3. 分析

  1. Python 默认函数的参数类型和返回类型为 int 型,当参数不是int型是,就需要告诉 Python 一个外来函数的形参类型和返回的值的类型。即需要给函数的两个属性 restype 和 argtypes 赋值。

  2. 对于 get_angle它的返回值类型是 float, 对应到 Python 里就是 c_float:

    复制代码
    1
    2
    lib.get_angle.restype = c_float

    如果函数的返回值是 void 那么你可以赋值为 None。另外,在不是太低的版本中,可以使用 Python 内置类型(文末表中最右边的一列)“描述”库函数的返回类型,但是,不可以用 Python 内置类型来描述库函数的参数。

  3. 由于函数的参数不是固定的数量,所以需要使用列表或者是元组来说明:

    复制代码
    1
    2
    3
    4
    lib.get_angle.argtypes = (c_float, c_float) #或,但是查找元组的效率更高 lib.get_angle.argtypes = [c_float, c_float]
  4. 接下来查看测试结果:
    命令行:

    在这里插入图片描述jupyter:
    在这里插入图片描述

附表:
在这里插入图片描述

最后

以上就是有魅力橘子最近收集整理的关于Python 使用ctypes调用 C 函数的全部内容,更多相关Python内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(90)

评论列表共有 0 条评论

立即
投稿
返回
顶部