我是靠谱客的博主 潇洒电灯胆,这篇文章主要介绍『Python CoolBook』使用ctypes访问C代码_上_用法讲解,现在分享给大家,希望可以做个参考。

一、动态库文件生成

源文件hello.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
#include "hello.h" #include <stdio.h> void hello(const char *name) { printf("Hello %s!n", 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

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#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头需要对应声明,如下结构会更保险,

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#ifndef __SAMPLE_H__ #define __SAMPLE_H__ #ifdef __cplusplus extern "C" { #endif /* 声明主体 */ #ifdef __cplusplus } #endif #endif

 

编译so动态库

复制代码
1
gcc -shared -fPIC -o libhello.so hello.c

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

二、使用python调用c函数

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

复制代码
1
2
3
4
5
6
7
8
9
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,之后的问题之后讲。

 

最后

以上就是潇洒电灯胆最近收集整理的关于『Python CoolBook』使用ctypes访问C代码_上_用法讲解的全部内容,更多相关『Python内容请搜索靠谱客的其他文章。

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

评论列表共有 0 条评论

立即
投稿
返回
顶部