python call so

时间:2021-10-08 18:46:33

作为一个老程序员,如果,python不能与c发生点儿关系,我都挺过意不去的啊

那么,就解决了这个强迫症吧,阿门!

//pycall.c

#include <stdio.h>
#include <stdlib.h>

int test(void* p, int len)
{
  return len;
}

#gcc -o pycall.c -c pycall.c

#gcc -o libpycall.so -shared -fPIC pycall.o

//test.py

import ctypes

ll = ctypes.cdll.LoadLibrary("./libpycall.so")
test = ll.test
test.argtypes = [ctypes.c_char_p,ctypes.c_int]
test.restypes = ctypes.c_int
sBuf = 'this is python'
nRst = test(sBuf, len(sBuf))
print 'res ', nRst

//result

# python test.py
res 14

Finally:

这下可以下班了吧?哈哈。。。