jeudi 30 août 2018

Calling a function of an object instance using embedded Python

I want to be able to run Python scripts in my app to allow automating stuff and modifying existing objects/calling methods of existing objects.

In my application there is a BasicWindow class and MainWindow class that derives from the former. For now at application start I initialize one instance of MainWindow. This object has many functions, among them there is one that loads files (LoadFile()), and I will use it as example here.

Lets say that I want to call that particular function (but not limited to that function, it is just an example of the functionality that I want to achieve from Python) of that particular object instance.

This method is not a static one. For this I am using Boost.Python and I am creating a module this way:

BOOST_PYTHON_MODULE(MyModule)
{

    MainWindow::PythonExpose(); //not really sure how to operate here
    //more stuff
}

The idea is that I could call from Python something like:

MainWindow.LoadFile()

or even better, just:

LoadFile()

One solution could be to create static, application scoped functions and then just expose those functions. In C++ I could find the particular instance of MainWindow: (both methods are static)

void AppHelper::LoadFile()
{
    GetMainWindow()->LoadFile();
}


void AppHelper::PythonExposeGlobal()
{
    using namespace boost::python;
    def("LoadFile", &AppHelper::LoadFile);
}

Is it possible to achieve this? The general question would be: is it possible to call methods of existing objects (in C++) from Python? If so, how to do it? If not, what can I do to mimic this behavior?

For example, I could easily enable scripting capabilities in my C# application and sharing instances of existing objects. (But of course C# has reflection).

Aucun commentaire:

Enregistrer un commentaire