如何在C / C ++应用程序中使用Pygtk?

时间:2014-12-12 21:10:21

标签: python c pygtk

我想在C / C ++应用程序中集成一个简单的Pygtk窗口(原因是pyGtk中先前设计的GUI将被集成到更大的GTK +(在C中)应用程序中)

我收到分段错误

我在这做了什么:

=====>在python(tmp.py)中:

#!/usr/bin/python

#from gi.repository import Gtk, Gio

win=Gtk.Window()
win.connect("delete-event",Gtk.main_quit)
win.show_all()
Gtk.main()

==>在C / C ++(simple.cpp)中:

我想执行那个小窗口

#include <Python.h>

int main(int argc, char *argv[])
{
   Py_SetProgramName(argv[0]);  /* optional but recommended */
   Py_Initialize();

   FILE *fp      = fopen ("tmp.py",   "r+");

   PyObject *mainModule = PyImport_AddModule("__main__");

   PyObject * subModules = PyList_New(0);
   PyList_Append(subModules, PyString_FromString("Gtk"));
   PyList_Append(subModules, PyString_FromString("Gio"));

   PyObject *Gtkstuff = PyImport_ImportModuleEx("gi.repository",NULL,NULL,subModules);

   PyObject *GtkMod =PyObject_GetAttr(Gtkstuff,PyString_FromString("Gtk"));
   PyObject *GioMod =PyObject_GetAttr(Gtkstuff,PyString_FromString("Gio"));

   PyModule_AddObject(mainModule, "Gtk", GtkMod);
   PyModule_AddObject(mainModule, "Gio", GioMod);

   PyRun_SimpleFile(fp,"tmp.py");
   Py_Finalize();
   return 0;
}

我编译的方式是:

g++ $(python-config --cflags) -o simple $(python-config --ldflags) ./simple.cpp

输出:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib64/python2.7/site-packages/gi/importer.py", line 68, in load_module
    dynamic_module._load()
  File "/usr/lib64/python2.7/site-packages/gi/module.py", line 291, in _load
    overrides_modules = __import__('gi.overrides', fromlist=[self._namespace])
  File "/usr/lib64/python2.7/site-packages/gi/overrides/Gtk.py", line 1502, in <module>
    initialized, argv = Gtk.init_check(sys.argv)
AttributeError: 'module' object has no attribute 'argv'
Traceback (most recent call last):
  File "tmp.py", line 5, in <module>
    win=Gtk.Window()
  File "/usr/lib64/python2.7/site-packages/gi/overrides/Gtk.py", line 415, in __init__
    if not initialized:
NameError: global name 'initialized' is not defined

1 个答案:

答案 0 :(得分:0)

这很有效,其余的代码对我来说没有意义,因为你可以在python脚本中进行所有的初始化。

#include <Python.h>

int main(int argc, char *argv[])
{
    Py_SetProgramName(argv[0]); /* optional but recommended */
    Py_Initialize();

    FILE *fp = fopen("tmp.py", "r");
    if (fp == NULL)
        return 2;

    PyRun_SimpleFile(fp, "tmp.py");
    Py_Finalize();

    fclose(fp);
    return 0;
}