c++ÈçºÎÏòpythonµÄ½Å±¾´«µÝÒ»¸öÀà×÷Ϊ²ÎÊý¡£

zghelp zghelp at mail.powerleader.com.cn
Tue Apr 26 04:57:03 EDT 2005


ʹÓõ½ÁËboost.python

Ö÷³ÌÐòÈçÏ£º

using namespace boost::python;

struct World
{
 void set(std::string msg) { this->msg = msg; }
 std::string greet() { return msg; }
 std::string msg;
};

BOOST_PYTHON_MODULE(hello)
{
 class_<World>("World")
  .def("greet", &World::greet)
  .def("set", &World::set)
  ;
}

int _tmain(int argc, _TCHAR* argv[])
{
 Py_Initialize();

 if (!Py_IsInitialized())
  return -1;

 inithello();

 PyRun_SimpleString("import sys");
 PyRun_SimpleString("sys.path.append('./')");

 PyObject* pName,*pModule,*pDict,*pFunc,*pArgs;

 pName = PyString_FromString("pytest");
 pModule = PyImport_Import(pName);
 if (!pModule)
  return -1;

 pDict = PyModule_GetDict(pModule);
 if (!pDict)
  return -1;

 pFunc = PyDict_GetItemString(pDict,"add");
 if (!pFunc || !PyCallable_Check(pFunc))
  return -1;

 World w;
 w.set("hi from main!");

 pArgs = PyTuple_New(3);
 PyTuple_SetItem(pArgs,0,Py_BuildValue("i",3));
 PyTuple_SetItem(pArgs,1,Py_BuildValue("i",4));
 PyTuple_SetItem(pArgs,2,Py_BuildValue("O",&w));

 try
 {
  PyObject_CallObject(pFunc,pArgs);
 }
 catch(error_already_set)
 {
  // handle the exception in some way
 }

 Py_DECREF(pName);
 Py_DECREF(pArgs);
 Py_DECREF(pModule);

 Py_Finalize();
 getchar();

 return 0;
}

½Å±¾ÈçÏ£º

import hello
from hello import *
def add(a,b,t):
 print "a + b = " + str(a+b)
 w = hello.World()
 w.set("hi from script!")
 print w.greet()
 print t.greet()
 return

½á¹ûÔËÐе½print t.greet()¾ÍÒì³£ÁË

ÔõôÑù²ÅÄÜ°ÑÒ»¸öÀà×÷Ϊ²ÎÊý´«µÝµ½pythonÖÐÈ¥°¢£¿





More information about the Python-list mailing list