zoukankan      html  css  js  c++  java
  • 『Python CoolBook』使用ctypes访问C代码_上_用法讲解

    一、动态库文件生成

    源文件hello.c

    #include "hello.h"
    #include <stdio.h>
    
    void hello(const char *name)
    {
        printf("Hello %s!
    ", name);
    }
    
    int factorial(int n)
    {
        if (n < 2)
            return 1;
        return factorial(n - 1) * n;
    }
    
    /* Compute the greatest common divisor */
    int gcd(int x, int y) {
        int g = y;
        while (x > 0) {
            g = x;
            x = y % x;
            y = g;
        }
        return g;
    }
    

      

    头文件hello.h

    #ifndef _HELLO_H_
    #define _HELLO_H_
    
    #ifdef __cplusplus
    extern "C" {
    #endif
    
    void hello(const char *);
    int factorial(int n);
    int gcd(int x, int y);
    
        
    #ifdef __cplusplus
    }
    #endif
    #endif

    结构体如果放在.h文件中和放在.c中写法没有区别,且重复定义会报错。

    如果使用了c++特性(.c文件需要是.cpp文件),.h头需要对应声明,如下结构会更保险,

    #ifndef __SAMPLE_H__
    #define __SAMPLE_H__
    
    #ifdef __cplusplus
    extern "C" {
    #endif
    
    /* 声明主体 */
    
    #ifdef __cplusplus
    }
    #endif
    
    #endif

    编译so动态库

    gcc -shared -fPIC -o libhello.so hello.c

    此时可以看到so文件于文件夹下。

    二、使用python调用c函数

    尝试使用ctypes模块载入库,并调用函数,

    from ctypes import cdll
    
    libhello= cdll.LoadLibrary("./libhello.so")
    libhello.hello('You')
    
    res1 = libhello.factorial(100)
    res2 = libhello.gcd(100, 2)
    print(libhello.avg)
    print(res1, res2)

    >>> python hello.py
    Hello Y!
    <_FuncPtr object at 0x7f9aedc3d430>
    0 2

    函数hello和我们预想的不一致,仅仅输出了首字母"Y",对于cookbook的其他c函数实际上我也做了导入,但是数据格式c和python是需要转换的,调用起来不是很容易的一件事,本篇重点在于成功导入python,之后的问题之后讲。

  • 相关阅读:
    一些简单的逻辑题
    3种数据类型之间的转换
    搭建selenium + Python环境的总结:
    杂记
    Eclemma的安装
    LR----实现WebService测试
    LR--实现HTTP协议的接口测试
    Loadrunner---解决乱码问题
    selenium常用API实例
    JMeter中响应数据显示乱码问题解决
  • 原文地址:https://www.cnblogs.com/hellcat/p/9058330.html
Copyright © 2011-2022 走看看