*********************************************
bridge between python and c introduction: connect.appen.com/qrp/core/login
*********************************************
wrapping c code in python
1. write c code
#include <stdio.h>
#include <stdlib.h>
int list_month(int i){
switch(i){
case 1:printf("Jan\n");
break;
case 2:printf("Feb\n");
break;
case 3:printf("Mar\n");
break;
case 4:printf("Apr\n");
break;
default:break;
}
}
2. compile it as shared library
gcc -shared -Wl,-soname,clib -o clib.so -fPIC clib.c
3. wrapping it in python
from ctypes import *
lib=CDLL("/home/tom/workspace/study/c/shared_so/clib.so")
lib.list_month(4)
step by step tutorial from: https://stackoverflow.com/questions/5081875/ctypes-beginner
本文详细介绍了一种在Python中调用C代码的方法,通过编写C语言代码、编译为共享库并使用ctypes模块在Python中调用,具体步骤包括:1. 编写C代码实现月份列表功能;2. 使用GCC编译为共享库;3. 在Python中通过ctypes导入共享库并调用C函数。
239

被折叠的 条评论
为什么被折叠?



