BCB(C++)调用Python

来源:互联网 发布:网络批发竞争 编辑:程序博客网 时间:2024/06/08 09:03
初始化Python
Py_Initialize();

初始化成功否
Py_IsInitialized()

載入執行模塊
AnsiString ModuleName;//為調用的Python模塊
PyObject *PyMod;
PyMod=PyImport_ImportModule(ModuleName.c_str());

模塊可用屬性、成員和函數清單
int sz;
const char *buf
PyObject item;
funlist=PyObject_Dir(PyMod);
sz=PyObject_Size(funlist);
cbb1->Items->Clear();
for (i = 0; i < sz; i++) {
    item=PyList_GetItem(funlist,i);
    PyObject_AsCharBuffer(item,&buf,&n);
    cbb1->Items->Add(AnsiString(buf));
}

獲取函數入口
PyObject *pyFun;
pyFun=PyObject_GetAttrString(PyMod,Function.c_str());

動態生成入口參數
參數是由分號(;)組成一字符串,每一個參數都是以字符串傳到python函數
AnsiString Args;//入口參數字符串
AnsiString af;//入口參數格式
PyObject *pyArgs;//入口參數內容
TStringList *sl;
PyObject *pyList;
PyObject *pytemp;
pyList=PyList_New(0);
sl=new TStringList();
sl->Delimiter=';';
sl->DelimitedText=Args;
for (i = 0; i < sl->Count; i++) {
    af+="s,";
    pytemp=PyString_FromString((const char*)sl->Strings[i].c_str());
    PyList_Append(pyList,pytemp);
}
af="("+af.SubString(1,af.Length()-1)+")";
pyArgs=PyList_AsTuple(pyList);

調用函數
PyObject *pyResult;
pyResult=PyEval_CallObject(pyFun,pyArgs);

獲取返回的數據類型
PyObject *pyType;
AnsiString type;//字符串形式的Python函數返回對象類型
pyType=PyObject_Str(PyObject_GetAttrString(pyResult,"__class__"));
if (pyType!=NULL) {
    pstr=PyString_AsString(pyType);
    type=AnsiString(pstr);
    n=type.Pos("'");
    type=type.SubString(n+1,type.Length()-n+1);
    n=type.Pos("'");
    type=type.SubString(1,n-1);
    mm1->Lines->Add("pyResult Type :"+type);
}


對返回對象進行格式化
根據數據類型type進行相應的格式化
PyObject *pytemp;
int i,n,sz;
const char *pstr;
if (type=="str") {
    PyArg_Parse(pyResult,"s",&pstr);
    mm1->Lines->Add("Return :"+AnsiString(pstr));
} else
    if (type=="int") {
    PyArg_Parse(pyResult,"i",&n);
    mm1->Lines->Add("Return :"+IntToStr(n));
} else
if (type=="list") {
    sz=PyObject_Size(pyResult);
    for (i = 0; i < sz; i++) {
        pytemp=PyList_GetItem(pyResult,i);
        PyObject_AsCharBuffer(pytemp,&pstr,&n);
        mm1->Lines->Add(AnsiString(pstr));
    }
}

釋放Python資源
Py_Finalize();
好像有個印象,它只對內置對象起作用,對於擴展模塊的資源分配需要手動釋放。