python调用c程序,通过动态链接库的方法比较麻烦,需要各种转换。另外一种比较直接的方法是使用pyobject扩展实现。
本文参考了https://www.cnblogs.com/hyyq/p/8995372.html。
python调用c程序
一、原理
此方法的步骤如下:
- 编写c程序。此处与正常的c程序是一样的。
- 编写封装程序。将步骤1的c程序进行封装,主要是参数的封装。因为python的变量是无法直接被c语言调用的,需要进行转换才行。
- 初始化。初始化的功能相当于注册了步骤1的函数。
- 编译
- 安装
- 通过import导入模块,进行调用
二、实现
1. 编写c程序
保留了参考链接中的3个函数,并扩展了字符查找功能。代码如下:
//py_test.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int fac(int n) {
if(n < 2)
return 1;
return n*fac(n-1);
}
char *reverse(char *s) {
//比如输入abcdefg,则返回gfedcba
char t,*p = s ,*q = (s+strlen(s)-1);
while(s && (p<q)) {
t = *p;
*p++ = *q;
*q-- = t;
}
return s;
}
int test(void) //测试main方法,改成普通的test方法
{
char s[1024];
printf("5! = %d\n",fac(5)); //5的阶乘
printf("10! = %d\n",fac(10)); // 10的阶乘
strcpy(s,"hello world");
printf("reversing 'hello world',we get '%s'\n",reverse(s));
return 0;
}
char *find_chr(char *s,