有了ctype之后,python用C语言的库不再需要用C写转换函数。
1. 载入动态库
#include <stdlib.h>
// file libHi.c
#include <stdio.h>
int hi(const char *str)
{
printf("Hi %s\n", str);
return 0;
}
然后编译为动态库
gcc -shared -fPIC -o libHi.so libHi.c
from ctypes import *
cdll.LoadLibrary('./libHi.so')
libhello = CDLL('./libHi.so')
# print(libhello)
print(libhello.hi)
print('exec hi ', libhello.hi(b'good'))
python3 ./ctypetest.py
<_FuncPtr object at 0x7febe41c>
Hi good
'exec hi ' 0