折騰了很久啦吧,終于找到可行的例子demo分3部分绿店,1, c module文件铸史,需要為python項(xiàng)目單獨(dú)建立#include#include#define min(a,b) (((a) < (b)) ? (a) : (b))
char data[1024];
void SetData(const char *str)
{
? ? printf("hello:%s\n",str);
strncpy(data, str, min(strlen(str) + 1, 1024));
}
const char *GetData()
{
return data;
}
PyDoc_STRVAR(PySetData_doc__, "\
測(cè)試\n\
\n\
PySetData(str)\n\
str: 出入的字符串\n\
返回: \n\
null \n\
");
static PyObject* PySetData(PyObject *self, PyObject *args)
{
const char* str = NULL;
if ( !PyArg_ParseTuple(args, "s", &str) )
{
return 0;
}
SetData(str);
Py_RETURN_NONE;
}
PyDoc_STRVAR(PyGetData_doc__, "\
打印數(shù)據(jù)\n\
\n\
PyGetData()\n\
返回: \n\
data \n\
");
static PyObject* PyGetData(PyObject *self, PyObject *args)
{
const char* str = NULL;
return PyString_FromString(GetData());
}
static PyMethodDef module_methods[] = {
{"py_set_data", PySetData, METH_VARARGS, PySetData_doc__},
{"py_get_data", PyGetData, METH_VARARGS, PyGetData_doc__},
{NULL}
};
PyMODINIT_FUNC? initpycallc()
{
PyObject *module = Py_InitModule3("pycallc", module_methods,
"python call c");
}
2鼻疮, 編譯以上c,可直接命令行用gcc 琳轿。判沟。。等利赋,也可用python 工具來(lái)編譯
建一個(gè)setup.py文件,內(nèi)容如下
from distutils.core import setup, Extension
module1 = Extension('pycallc',
? ? ? ? ? ? ? ? ? ? sources = ['pycallc.c'])
setup (name = 'pycallc',
? ? ? version = '1.0',
? ? ? description = 'This is a demo package',
? ? ? ext_modules = [module1])
然后命令行執(zhí)行
python setup.py build
會(huì)生成pycallc.so文件猩系, 拷貝該文件到py的demo同目錄 (也可其它目錄媚送,現(xiàn)在簡(jiǎn)單點(diǎn))
3, python的demo
import pycallc
print "kkkk"
def test():
print 'in python : ', pycallc.py_get_data()
pycallc.py_set_data("change hello world!")
print pycallc.py_get_data()
if __name__ == "__main__" :
test()
可能在py文件中import pycallc一直顯示紅色寇甸,讓我以為一直是錯(cuò)誤的塘偎,事實(shí)目前這樣就ok。