embedding und extending an c++ beispiel
Verfasst: Donnerstag 4. Februar 2010, 20:12
Ich hoffe, ich fange nicht an euch zu nerven.
Ich habe mir überlegt wie ich in einem C++ Python aufrufen kann. Ich habe ein minimales Beispiel, das ich aus verschiednen Sourcen zusammengemergt habe, gemacht (ich weiß dass längerer Code nicht so beliebt ist). Also ich hoffe er ist nicht zu lange.
Das "embedding" funktioniert ja schon mal:
Was ich jetzt möchte, ist von (momentan ist eine print anweisung in file1.py und file2.py):
Dass ich einem "this" pointer mitgeben kann. im Python script sagt er dann (pseudo code):
Ich habe mir überlegt wie ich in einem C++ Python aufrufen kann. Ich habe ein minimales Beispiel, das ich aus verschiednen Sourcen zusammengemergt habe, gemacht (ich weiß dass längerer Code nicht so beliebt ist). Also ich hoffe er ist nicht zu lange.
Das "embedding" funktioniert ja schon mal:
Code: Alles auswählen
//g++ main.cc -o simple `pkg-config gtkmm-2.4 --cflags --libs` -I/usr/include/python2.6 -lpython2.6
#include <iostream>
#include <gtkmm.h>
#include <gtkmm/main.h>
#include <gtkmm/messagedialog.h>
#include "Python.h"
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_button_info_clicked();
//Child widgets:
Gtk::VButtonBox m_ButtonBox;
Gtk::Button m_Button_Info;
};
ExampleWindow::ExampleWindow()
: m_Button_Info("Show Info MessageDialog")
{
set_title("Gtk::MessageDialog example");
add(m_ButtonBox);
m_ButtonBox.pack_start(m_Button_Info);
m_Button_Info.signal_clicked().connect(sigc::mem_fun(*this,
&ExampleWindow::on_button_info_clicked) );
show_all_children();
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_button_info_clicked()
{
Py_Initialize();
PyRun_SimpleString("import sys; import os;");
PyRun_SimpleString("sys.path.append(os.getcwd())");
PyObject* main_module =
PyImport_AddModule("__main__");
// Get the main module's dictionary
// and make a copy of it.
PyObject* main_dict =
PyModule_GetDict(main_module);
PyObject* main_dict_copy =
PyDict_Copy(main_dict);
// Execute two different files of
// Python code in separate environments
FILE* file_1 = fopen("file1.py", "r");
PyRun_File(file_1, "file1.py",
Py_file_input,
main_dict, main_dict);
FILE* file_2 = fopen("file2.py", "r");
PyRun_File(file_2, "file2.py",
Py_file_input,
main_dict_copy, main_dict_copy);
Py_Finalize();
Gtk::MessageDialog dialog(*this, "This is an INFO MessageDialog");
dialog.set_secondary_text(
"And this is the secondary text that explains things.");
dialog.run();
}
int main(int argc, char *argv[])
{
Gtk::Main kit(argc, argv);
ExampleWindow window;
//Shows the window and returns when it is closed.
Gtk::Main::run(window);
return 0;
}
Dass ich einem "this" pointer mitgeben kann. im Python script sagt er dann (pseudo code):
Code: Alles auswählen
import examplewindow
examplewindow. m_Button_Info.set_label("neu")