[C++-sig] Exposing C++ Class instances to Python
xin
xin at xlevus.net
Sat Aug 7 07:02:17 CEST 2004
So I have the following code.
/***** START Point.cpp *****/
struct Point {
Point() { count = 0; size = 1; script="testScript"}
int count;
int size;
char *script;
};
BOOST_PYTHON_MODULE(HgSharedLib)
{
class_<Point>("Point")
.def_readonly("count", &Point::count)
.def_readwrite("size", &Point::size);
}
/***** END Point.cpp *****/
/***** START PyController.cpp ******/
PyObject *pyController::getPyFunc(char *moduleName, char *functionName)
{
/* Courtsey of Jeffrey Holle */
PyObject *pModule = PyImport_ImportModule(moduleName);
if(pModule == NULL) std::cout << "The Python Module \"" << moduleName << "\"
is not available" << std::endl;
PyObject *pDict = PyModule_GetDict(pModule);
if(pDict == NULL) std::cout << "Failed to Aqquire dictionary of \"" <<
moduleName << "\"" << std::endl;
PyObject *pFunc = PyDict_GetItemString(pDict,functionName);
if(pFunc == NULL) std::cout << "Failed to find requested python function \""
<< functionName << "\"" << std::endl;
Py_DECREF(pModule);
return pFunc;
}
bool pyController::runScript(Point &dest)
{
Py_Initialize();
PyRun_SimpleString("import sys\nsys.path.append(\"/home/xin/code/Hg/src\")");
PyObject *pFunc = getPyFunc(dest.script, "TestFunc");
std::cout << "Start Size: " << dest.size << std::endl;
// Run TestFunc Here
std::cout << "End Size: " << dest.size << std::endl;
Py_Finalize();
}
/***** END PyController.cpp *****/
/**** START main.cpp *****/
int main()
{
Point foo;
pyController PyCon;
PyCon.runScript(foo);
return 0
}
/**** END main.cpp *****/
/***** START testScript.py *****/
def TestFunc (pt):
pt.size = 5
return pt.size
/***** END testScript.py *****/
My overall goal is to run TestFunc on foo. And the output to end up like.
Start Size: 1
End Size: 5
What Im unsure of, is how to turn foo into a PyObject to then run the python
FUnction TestFunc with the new PyObject (foo) as an arguement. ( Python Equiv:
TestFunc(foo) )
I hope Im making sense..
Thanks for you help
More information about the Cplusplus-sig
mailing list