当前位置: 首页 > 后端技术 > Python

调用HighLevelPythonAPI

时间:2023-03-26 15:36:46 Python

C/C++程序中的PythonAPI类型分为HighLevelAPI和LowLevelAPI。低级API是API的基础。当调用HighLevelAPI时,Python基础库会为C/C++程序创建一个全局的运行环境。示例类ScapyAdapter{private:ScapyAdapter(){Py_Initialize();py_global_object=PyModule_GetDict(PyImport_AddModule("__main__"));PyRun_SimpleStringFlags("fromscapyimport*",nullptr);PyRun_SimpleStringFlags("fromscapy.layers.inetimport*",nullptr);PyRun_SimpleStringFlags("fromscapy.layers.inet6import*",nullptr);PyRun_SimpleStringFlags("fromscapy.layers.pppimport*",nullptr);PyRun_SimpleStringFlags("fromscapy.layers.vxlanimport*",nullptr);PyRun_SimpleStringFlags("fromscapy.contrib.nshimport*",nullptr);}staticstd::shared_ptrptr_instance_;structPyObjectDeleter{voidoperator()(PyObject*obj)const{if(obj)Py_DECREF(obj);}};使用PyObjectPtr=std::unique_ptr;PyObject*py_global_object{nullptr};public:virtual~ScapyAdapter(){if(PyErr_Occurred()){PyErr_Print();PyErr_Clear();}Py_Finalize();}ssize_tConstructPacket(constchar*expr,char*buffer,size_tsz_buffer){charcstr_expr[4096];snprintf(cstr_expr,sizeof(cstr_expr),“pkt_object=%s”,expr);PyObjectPtrpy_expr_object=PyObjectPtr(PyRun_StringFlags(cstr_expr,Py_single_input,py_global_object,py_global_object,nullptr));如果(py_expr_object==nullptr){PyErr_Print();PyErr_Clear();返回-1;}PyObjectPtrpy_pkt_object=PyObjectPtr(PyDict_GetItemString(py_global_object,"pkt_object"));如果(py_pkt_object==nullptr){PyErr_Print();PyErr_Clear();返回-2;}PyObjectPtrpy_pkt_bytes=PyObjectPtr(PyObject_Bytes(py_pkt_object.get()));constchar*pkt_ptr=PyBytes_AsString(py_pkt_bytes.get());无符号整数pkt_len=PyBytes_Size(py_pkt_bytes.get());memcpy(缓冲区,pkt_ptr,pkt_len);返回pkt_len;}staticstd::shared_ptrScapyAdapterInstance(){if(ptr_instance_!=nullptr)return:ptr_instance_:shared_ptr(newScapyAdapter());返回ptr_instance_;}};调用PyRun_StringFlags()时,需要填写start参数。该参数在compiler.h中定义,其含义在https://docs中。这在python.org/3/c-api/veryhigh.html文档中进行了解释。在调用Py_Finalize()之前,注意清除所有Python解释器抛出的异常,否则会出错。在Python官网上,HighlevelAPI的文档和例子都不是很全面,尤其是需要和LowLevelAPI结合的时候。可以参考https://hg.python.org/cpython/file/tip/Python/pythonrun.c