1)首先,創建一個.c文件,其大體內容如下:
2 #include <Python.h>
99 char * extract(char * path) //想要調用的函數
100 {
112 char * Q = (char * )malloc(3*sizeof(char));
。
。
。
149 return Q;
150 }
151
152
153 PyObject* wrap_extract(PyObject* self, PyObject* args) //與python的接口函數,python中實際上調用的是這個函數,由這個函數調用真正的函數
154 {
155 int n;
156 char * path,*result;
157 if (! PyArg_ParseTuple(args, "s:extract", &path)) //進行參數傳遞,把python中的參數轉到c語言中
158 return NULL;
159 result = extract(path);
160 return Py_BuildValue("s", result);
161 }
162
163 static PyMethodDef extractMethods[] =
164 {
165 {"extract", wrap_extract, METH_VARARGS, "by DChipNau"},
166 {NULL, NULL}
167 };
168
169 void initextract() //當import這個模塊之后會調用這個函數。
170 {
171 PyObject* m;
172 m = Py_InitModule("extract", extractMethods);
173 }
2)然后使用如下命令進行編譯:
gcc -fPIC extract.c -o extract.so -shared -I/usr/include/python2.7 -I/usr/lib/python2.7/config
3)在python中調用方法如下:
import extract
string = extract.extract(str(out_file))
PS:參數傳遞時直接傳遞int數組真是相當難受