这篇文章介绍在python中调用clib定义的函数,分别是ctypes/Python API的形式。
1. ctypes
1.1 一个简单的例子
首先准备hello.c文件:
#include
void hello()
{
printf("Hello, World!\n");
}
其次准备makefile:
ALL:
gcc -c -fPIC -o hello.o hello.c
gcc -shared -o libhello.so hello.o
执行make生成动态库
再编写hello.py:
#!/usr/bin/env python
# -*- coding=utf-8 -*-
from ctypes import cdll, CDLL
from ctypes import create_string_buffer
from ctypes import c_int, c_ulonglong
# 有两种引入方式
# hellolibc = cdll.LoadLibrary('./libhello.so')hellolibc = CDLL('./libhello.so')
hellolibc.hello()
一个简单的例子就编写完成了。
1.2 注意事项
ctypes在使用上有很多需要注意的地方,这里介绍下一些常见的问题。
1.2.1 传入可变字符串
更新我们的hello.c文件:
void hello()
{
printf("Hello, World!\n");
}
void modify(char* str)
{
int l = strlen(str);
str[l] = 'C';
str[l + 1] = '\0';
}
该方法对传入的字符串末尾追加一个字符’C’,执行make生成动态库。
更新hello.py文件调用该方法:
#!/usr/bin/env python
# -*- coding=utf-8 -*-
from ctypes import cdll, CDLL
from ctypes import create_string_buffer
from ctypes import c_int, c_ulonglong
hellolibc = CDLL('./libhello.so')
# p is not immutablep = 'hello'
print p # hellohellolibc.modify(p)
# p is unchangedprint p # hello
#hellolibc.hello()
# p is immutablep = create_string_buffer("hello")
print p.value # hellohellolibc.modify(p)
# p is changedprint p.value # helloC
其中第一种直接传入的