python擴充:封裝C++類

來源:互聯網
上載者:User

轉載註明出處:http://blog.csdn.net/you_lan_hai/article/details/8597451

// TestPython.cpp : 定義控制台應用程式的進入點。// author: 遊藍海// blog: http://blog.csdn.net/you_lan_hai#include "stdafx.h"#include <iostream>using namespace std;#include "../python/Include/Python.h"#include "../python/Include/structmember.h"//有多個參數的python匯出函數static PyObject* py_test(PyObject* self, PyObject * args){cout<<"this message comes from C++"<<endl;Py_IncRef(Py_None);return Py_None;}//方法定義static PyMethodDef lazyMethods[] ={{"test", PyCFunction(py_test), METH_VARARGS, "just for test"},{NULL, NULL, NULL, NULL}, //結束標誌};//python匯出類class TestPyClass : public PyObject{public:TestPyClass(PyTypeObject * pType): id_(0), score_(99){if(PyType_Ready(pType) < 0)  {cout<<"PyType_Ready faild."<<endl;} PyObject_INIT(this, pType);}virtual ~TestPyClass(){}static PyObject* py_new(PyTypeObject * pType, PyObject *, PyObject *){return new TestPyClass(pType);}static void py_dealloc(PyObject * self){delete (TestPyClass*)self;}//init方法。static int py_init(PyObject * self, PyObject * args, PyObject *){TestPyClass* pThis = (TestPyClass*)self;if(!PyArg_ParseTuple(args, "ii", &pThis->id_, &pThis->score_)){return 0;}return 1;}PyObject* py_test(PyObject * args){cout<<"this message comes from TestPyClass."<<endl;Py_IncRef(Py_None);return Py_None;}//匯出函數static PyObject* _py_test(PyObject* self, PyObject * args){return ((TestPyClass*)self)->py_test(args);}int id_;int score_;};/*如果類中有虛函數,則類對象開始地址為一個虛函數表的地址。由於PyObject沒有虛函數,而子類有虛函數,則子類與基類不共起始地址。*/#define offsetofVirtual(type, member) ( (int) & ((type*)0) -> member - sizeof(void*))//成員變數static PyMemberDef TestClassMembers[] ={{"id", T_INT, offsetofVirtual(TestPyClass, id_), 0, "id"},{"score", T_INT, offsetofVirtual(TestPyClass, score_), 0, "score"},{NULL, NULL, NULL, 0, NULL},};//成員函數static PyMethodDef TestClassMethods[] ={{"test", PyCFunction(TestPyClass::_py_test), METH_VARARGS, "just for test"},{NULL, NULL, NULL, NULL},};//類類型static PyTypeObject TestPyClass_Type = {PyVarObject_HEAD_INIT(&PyType_Type, 0)"TestPyClass",sizeof(TestPyClass),0,(destructor)TestPyClass::py_dealloc,/* tp_dealloc */0,/* tp_print */0,                                          /* tp_getattr */0,                                          /* tp_setattr */0,                                          /* tp_compare */0,/* tp_repr */0,                                          /* tp_as_number */0,/* tp_as_sequence */0,/* tp_as_mapping */0,/* tp_hash */0,                                          /* tp_call */0,                                          /* tp_str */0,/* tp_getattro */0,                                          /* tp_setattro */0,                                          /* tp_as_buffer */Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE ,/* tp_flags */0,/* tp_doc */0,/* tp_traverse */0,/* tp_clear */0,/* tp_richcompare */0,                                          /* tp_weaklistoffset */0,/* tp_iter */0,                                          /* tp_iternext */TestClassMethods,                           /* tp_methods */TestClassMembers,                           /* tp_members */0,                                          /* tp_getset */0,                                          /* tp_base */0,                                          /* tp_dict */0,                                          /* tp_descr_get */0,                                          /* tp_descr_set */0,                                          /* tp_dictoffset */(initproc)TestPyClass::py_init,             /* tp_init */0,/* tp_alloc */(newfunc)TestPyClass::py_new,               /* tp_new */0,/* tp_free */};void initLazy(void){PyObject* pModule = Py_InitModule("Lazy", lazyMethods);if (pModule){Py_IncRef((PyObject*)&TestPyClass_Type);PyModule_AddObject(pModule, "TestClass", (PyObject*)&TestPyClass_Type);}}int _tmain(int argc, _TCHAR* argv[]){Py_SetPythonHome("F:/workspace/test/python");Py_Initialize();if (!Py_IsInitialized()){cout<<"Py_Initialize faild! "<<endl;PyErr_Print();return 0;}cout<<"Python initialize success."<<endl;initLazy();PyRun_SimpleString("import Lazy");PyRun_SimpleString("Lazy.test()");PyRun_SimpleString("a = Lazy.TestClass(2, 3)");PyRun_SimpleString("print dir(a)");PyRun_SimpleString("a.test()");PyRun_SimpleString("print 'a.id = ', a.id, ', a.score = ', a.score");#if 0//測試對象大小。含虛函數的類,會大4個位元組。 cout<<"sizeof(PyObject)"<<sizeof(PyObject)<<endl;cout<<"sizeof(TestPyClass)"<<sizeof(TestPyClass)<<endl;TestPyClass testPy(&TestPyClass_Type);cout<<"testPy addr:"<<&testPy<<" "<<(PyObject*)&testPy<<", id:"<<&(((TestPyClass*)0)->id_)<<endl;#endifPy_Finalize();return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.