有了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