Hi

I've got an embedded python system up and running, for evaluation purposes.

I am able to expose c++ modules to python, create c++ classes in python, and extract and use those python types in c++! Cool!

However, what if I want to pass a c++ type to a python class? Is there some way to covnert my class, Logger in this case, to an bpy object, or some other way?

Here's my code:

// main.cpp
#include <iostream>
#include <boost/python.hpp>
#include <boost/detail/lightweight_test.hpp>
#include "../logger/logger.h"

using namespace boost::python;
using namespace std;

BOOST_PYTHON_MODULE(hybrid)
{
   class_<Logger, boost::noncopyable>("Logger")
       .def("StartLogToFile", &Logger::StartLogToFile)
       .def("SYS", &Logger::SYS)
       ;
}

int main(int, char **)
{
   Py_Initialize();
   try
   {
       // Get main module and namespace
object pyModule_main(handle<>(borrowed(PyImport_AddModule("__main__"))));
       object pyNamespace_main = pyModule_main.attr("__dict__");

       // expose boost python modules
       inithybrid();
exec("print 'Embedded python....'\n", m_pyNamespace_main); // import another module
       object pyModule_test = import("test");
object pyNamespace_test = pyModule_test.attr("__dict__"); // c++ object, creating in python, extracted and used in c++! THIS WORKS
       Logger* log = extract<Logger*>(pyNamespace_test["pyLogger"]);
log->SYS("C++ using an object created in python embedded in c++!", 0);

       Logger* cppLogger = new Logger;
       cppLogger->StartLogToFile("cppLog.txt");
       //Push c++ logger into python namespace THIS DOESN'T!
       pyNamespace_test["logger"] = cppLogger;

object ignored = exec("useCppLogger()", m_pyNamespace_test, m_pyNamespace_test);

   }
   catch (error_already_set)
   {
       PyErr_Print();
   }

   delete cppLogger;
}


# test.py
import hybrid
pyLogger = hybrid.Logger()
pyLogger.StartLogToFile("pyLogger.txt")
pyLogger.SYS("Python using a python Logger. wow...")

def useCppLogger():
   # cppLogger has been pushed into module namespace by c++
   global cppLogger
   cppLogger.SYS("Python using a Logger class passed from c++")

#

Thanks for any help!

Simon


_______________________________________________
Cplusplus-sig mailing list
Cplusplus-sig@python.org
http://mail.python.org/mailman/listinfo/cplusplus-sig

Reply via email to