當前位置:首頁 » 編程語言 » c調用python的函數

c調用python的函數

發布時間: 2024-12-04 04:04:52

㈠ 【python-C相互調用】python里的dict如何作為參數傳入.so中的c語言函數

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

staticPyObject*
wmf_reverse(PyObject*self,PyObject*args,PyObject*kwargs){
staticchar*kwlist[]={"name",NULL};
char*name=NULL;
PyObject*retval=NULL;

//問題1:只取一個字元串,format應該是"s"
//>>>if(PyArg_ParseTupleAndKeywords(args,keyds,"isi",kwlist,&name))
if(PyArg_ParseTupleAndKeywords(args,kwargs,"s",kwlist,&name)){
retval=(PyObject*)Py_BuildValue("i",1);
printf("%s ",name);
//問題2:不要釋放
//>>>free(name);
}else{
retval=(PyObject*)Py_BuildValue("i",0);
}
returnretval;
}

staticPyMethodDef
wmf_methods[]={
{"reverse",(PyCFunction)wmf_reverse,METH_VARARGS|METH_KEYWORDS,"reverse"},
//問題3:方法定義表,應該用一條空記錄來表示結束。
{NULL,NULL,0,NULL},
};

//問題4:沒有定義mole
staticstructPyMoleDef
wmf_mole={
PyMoleDef_HEAD_INIT,
"wmf",/*nameofmole*/
NULL,/*moledocumentation,maybeNULL*/
-1,/*sizeofper-interpreterstateofthemole,
or-.*/
wmf_methods,
};

//問題5:入口函數要聲明為:PyMODINIT_FUNC
PyMODINIT_FUNC
PyInit_wmf(void){
//問題6:Py_InitMole要初始化的是模塊,不是方法。所以傳方法定義是錯誤的。
//另外,python2.x是用Py_Init_mole,python3.x改用PyMole_Create了。
//兩者略有差別,自己注意一下吧。這里我用的是python3.x。
//Py_InitMole("wmf",ExtestMethods);
PyObject*m;
m=PyMole_Create(&wmf_mole);
if(m==NULL){
returnNULL;
}
returnm;
}

熱點內容
python爬蟲數據分析 發布:2025-09-16 19:04:15 瀏覽:533
安卓錄屏大師怎麼直播 發布:2025-09-16 18:51:52 瀏覽:929
電腦怎麼解壓文件步驟 發布:2025-09-16 18:32:10 瀏覽:390
編譯器默認構造函數內聯 發布:2025-09-16 18:30:40 瀏覽:260
密碼忘了怎麼改 發布:2025-09-16 18:29:54 瀏覽:160
金盾加密視頻版本識別 發布:2025-09-16 18:22:02 瀏覽:551
二手車寶馬320li17年有哪些配置 發布:2025-09-16 17:59:32 瀏覽:890
c語言n次方怎麼輸入 發布:2025-09-16 17:51:17 瀏覽:910
完美國際密碼在哪裡改 發布:2025-09-16 17:43:44 瀏覽:908
網盤解壓包怎麼打開 發布:2025-09-16 16:59:19 瀏覽:819