Gui python para programa C

Hola a todos, finalmente despues de leerme varias paginas de internet sobre el tema, he conseguido parcialmente comunicar una aplicacion python GUI con un programa en C.
Pero lamentablemente tengo algunos problemas que no he podido solucionar.

Para compilar el programa uso: gcc ccalc.c -g -fPIC -I/usr/include/python2.6 -shared -L/usr/bin -lpython2.6 -o ccalc.so
Para ejecutar el programa lanzo: python calc_fx.py

Adjunto codigos fuentes de archivos.

Este archivo queda intacto, no se modifica.
calc.py

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'calc.ui'
#
# Created: Wed Oct 14 02:06:16 2009
#      by: PyQt4 UI code generator 4.4.4
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

class Ui_calc(object):
    def setupUi(self, calc):
        calc.setObjectName("calc")
        calc.resize(400, 180)
        self.label = QtGui.QLabel(calc)
        self.label.setGeometry(QtCore.QRect(20, 13, 80, 31))
        self.label.setObjectName("label")
        self.label_2 = QtGui.QLabel(calc)
        self.label_2.setGeometry(QtCore.QRect(20, 60, 80, 18))
        self.label_2.setObjectName("label_2")
        self.label_3 = QtGui.QLabel(calc)
        self.label_3.setGeometry(QtCore.QRect(20, 100, 70, 18))
        self.label_3.setObjectName("label_3")
        self.num1 = QtGui.QLineEdit(calc)
        self.num1.setGeometry(QtCore.QRect(100, 14, 113, 30))
        self.num1.setObjectName("num1")
        self.num2 = QtGui.QLineEdit(calc)
        self.num2.setGeometry(QtCore.QRect(100, 55, 113, 28))
        self.num2.setObjectName("num2")
        self.result = QtGui.QLineEdit(calc)
        self.result.setGeometry(QtCore.QRect(100, 96, 113, 28))
        self.result.setObjectName("result")
        self.sum = QtGui.QPushButton(calc)
        self.sum.setGeometry(QtCore.QRect(240, 10, 106, 27))
        self.sum.setObjectName("sum")
        self.res = QtGui.QPushButton(calc)
        self.res.setGeometry(QtCore.QRect(240, 40, 106, 27))
        self.res.setObjectName("res")
        self.mul = QtGui.QPushButton(calc)
        self.mul.setGeometry(QtCore.QRect(240, 70, 106, 27))
        self.mul.setObjectName("mul")
        self.div = QtGui.QPushButton(calc)
        self.div.setGeometry(QtCore.QRect(240, 100, 106, 27))
        self.div.setObjectName("div")
        self.salir = QtGui.QPushButton(calc)
        self.salir.setGeometry(QtCore.QRect(130, 140, 106, 27))
        self.salir.setObjectName("salir")

        self.retranslateUi(calc)
        QtCore.QObject.connect(self.salir, QtCore.SIGNAL("clicked()"), calc.close)
        QtCore.QMetaObject.connectSlotsByName(calc)

    def retranslateUi(self, calc):
        calc.setWindowTitle(QtGui.QApplication.translate("calc", "Calculadora", None, QtGui.QApplication.UnicodeUTF8))
        self.label.setText(QtGui.QApplication.translate("calc", "Número 1", None, QtGui.QApplication.UnicodeUTF8))
        self.label_2.setText(QtGui.QApplication.translate("calc", "Número 2", None, QtGui.QApplication.UnicodeUTF8))
        self.label_3.setText(QtGui.QApplication.translate("calc", "Resultado", None, QtGui.QApplication.UnicodeUTF8))
        self.sum.setText(QtGui.QApplication.translate("calc", "Sumar", None, QtGui.QApplication.UnicodeUTF8))
        self.res.setText(QtGui.QApplication.translate("calc", "Restar", None, QtGui.QApplication.UnicodeUTF8))
        self.mul.setText(QtGui.QApplication.translate("calc", "Multiplicar", None, QtGui.QApplication.UnicodeUTF8))
        self.div.setText(QtGui.QApplication.translate("calc", "Dividir", None, QtGui.QApplication.UnicodeUTF8))
        self.salir.setText(QtGui.QApplication.translate("calc", "Salir", None, QtGui.QApplication.UnicodeUTF8))

Archivo python con las funciones, problemas que tengo:
1.- valor recibido desde C es:
si se imprime el valor como texto (por eso he usado "%s" % (cresult) ) es: <__main__.calc object at 0x7f7aee08f848>
el codigo 0x7f... siempre cambia en cada ejecucion.
2.- En la funcion ccalc.triggerEvent(5, 2), le he pasado los valores iniciales para comprobar el funcionamiento del archivo C.
Pero necesito que tome los valores que tienen self.num1 = QtGui.QLineEdit(calc) y self.num2 = QtGui.QLineEdit(calc) del archivo calc.py
he tratado con calc.num1.setText(), setupUi.num1.setText(), Ui_calc.num1.setText() pero no es reconocido.

calc_fx.py

# -*- coding: utf-8 -*-

import sys
from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import *
from calc import Ui_calc

class calc(QWidget, Ui_calc):
  def __init__(self, parent = None):
    QWidget.__init__(self, parent)
    self.setupUi(self)
    self.connect(self.sum, SIGNAL("clicked()"),self.sumar)
    self.connect(self.res, SIGNAL("clicked()"),self.restar)
    self.connect(self.mul, SIGNAL("clicked()"),self.multiplicar)
    self.connect(self.div, SIGNAL("clicked()"),self.dividir)

  def sumar(cresult):
    return cresult.result.setText("%s" % (cresult))
 
  def restar(cresult):
    return cresult.result.setText('')

# Python calls a C extension module to register handlers, trigger events
import ccalc
ccalc.setHandler(calc.sumar)
ccalc.triggerEvent(5, 2)

if __name__ == "__main__":
  app = QApplication(sys.argv)
  window = calc()
  window.show()
  sys.exit(app.exec_())

Archivo C, dudas que tengo:
El archivo al parecer esta trabajando bien a excepcion del valor que devuelve a python.
Si se agrega un printf bajo las lineas:
args = Py_BuildValue("d", cresult);
pyresult = PyEval_CallObject(Handler, args);
se aprecia que el valor de args y pyresult son correctos.
El problema esta en Py_BuildValue("d", cresult); al parecer no esta pasando el valor en forma adecuada.

ccalc.c

#include <Python.h>
#include <stdlib.h>

static PyObject *Handler = NULL;     // keep Python object in C

void Route_Event(double cresult) {
    double *cres;
    PyObject *args, *pyresult;
   
    args = Py_BuildValue("d", cresult);   /* make arg-list */
    pyresult = PyEval_CallObject(Handler, args);      /* apply: run a call */
    Py_DECREF(args);                              /* add error checks */

    if (pyresult != NULL) {
        PyArg_Parse(pyresult, "f", &cres);
        printf("%f\n", cres);
        Py_DECREF(pyresult);
    }
}

static PyObject *
Register_Handler(PyObject *self, PyObject *args) {
    /* save Python callable object */
    Py_XDECREF(Handler);                 /* called before? */
    PyArg_Parse(args, "O", &Handler);    /* one argument? */
    Py_XINCREF(Handler);                 /* add a reference */
    Py_INCREF(Py_None);                  /* return 'None': success */
    return Py_None;
}

// let Python simulate event caught by C
static PyObject *
Trigger_Event(PyObject *self, PyObject *args) {
    double num1 = 0, num2 = 0;
    double cresult;
    PyArg_ParseTuple(args,"dd", &num1, &num2); // carga variables python en punteros de C.
    cresult = num1 + num2;
    Route_Event(cresult);
    Py_INCREF(Py_None);
    return Py_None;
}

static struct PyMethodDef ccalc_methods[] = {
    {"setHandler", Register_Handler},
    //{"triggerEvent", Trigger_Event},
    {"triggerEvent",  Trigger_Event, METH_VARARGS},
    {NULL, NULL}
};

// this is called by Python on first "import ccalc"
void initccalc() {
    (void) Py_InitModule("ccalc", ccalc_methods);
}

Saludos y muchas gracias por vuestra ayuda.

Linux_mv escribió:

Archivo python con las funciones, problemas que tengo:
1.- valor recibido desde C es:
si se imprime el valor como texto (por eso he usado "%s" % (cresult) ) es: <__main__.calc object at 0x7f7aee08f848>
el codigo 0x7f... siempre cambia en cada ejecucion.

prueba con un print(dir(cresult)) para ver que funciones tiene ese valor devuelto

Linux_mv escribió:

2.- En la funcion ccalc.triggerEvent(5, 2), le he pasado los valores iniciales para comprobar el funcionamiento del archivo C.
Pero necesito que tome los valores que tienen self.num1 = QtGui.QLineEdit(calc) y self.num2 = QtGui.QLineEdit(calc) del archivo calc.py
he tratado con calc.num1.setText(), setupUi.num1.setText(), Ui_calc.num1.setText() pero no es reconocido.

self.num1.text(), http://doc.trolltech.com/4.7/qlineedit.html#text-prop
De C ni idea

Respecto de tus consultas, las respuestas son:

print(dir(cresult))

['DrawChildren', 'DrawWindowBackground', 'IgnoreMask', 'PaintDeviceMetric', 'PdmDepth', 'PdmDpiX', 'PdmDpiY', 'PdmHeight', 'PdmHeightMM', 'PdmNumColors', 'PdmPhysicalDpiX', 'PdmPhysicalDpiY', 'PdmWidth', 'PdmWidthMM', 'RenderFlag', 'RenderFlags', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'acceptDrops', 'accessibleDescription', 'accessibleName', 'actionEvent', 'actions', 'activateWindow', 'addAction', 'addActions', 'adjustSize', 'autoFillBackground', 'backgroundRole', 'baseSize', 'blockSignals', 'changeEvent', 'childAt', 'childEvent', 'children', 'childrenRect', 'childrenRegion', 'clearFocus', 'clearMask', 'close', 'closeEvent', 'colorCount', 'connect', 'connectNotify', 'contentsMargins', 'contentsRect', 'contextMenuEvent', 'contextMenuPolicy', 'create', 'cursor', 'customContextMenuRequested', 'customEvent', 'deleteLater', 'depth', 'destroy', 'destroyed', 'devType', 'disconnect', 'disconnectNotify', 'div', 'dragEnterEvent', 'dragLeaveEvent', 'dragMoveEvent', 'dropEvent', 'dumpObjectInfo', 'dumpObjectTree', 'dynamicPropertyNames', 'effectiveWinId', 'emit', 'enabledChange', 'ensurePolished', 'enterEvent', 'event', 'eventFilter', 'find', 'findChild', 'findChildren', 'focusInEvent', 'focusNextChild', 'focusNextPrevChild', 'focusOutEvent', 'focusPolicy', 'focusPreviousChild', 'focusProxy', 'focusWidget', 'font', 'fontChange', 'fontInfo', 'fontMetrics', 'foregroundRole', 'frameGeometry', 'frameSize', 'geometry', 'getContentsMargins', 'grabGesture', 'grabKeyboard', 'grabMouse', 'grabShortcut', 'graphicsEffect', 'graphicsProxyWidget', 'handle', 'hasFocus', 'hasMouseTracking', 'height', 'heightForWidth', 'heightMM', 'hide', 'hideEvent', 'inherits', 'inputContext', 'inputMethodEvent', 'inputMethodHints', 'inputMethodQuery', 'insertAction', 'insertActions', 'installEventFilter', 'isActiveWindow', 'isAncestorOf', 'isEnabled', 'isEnabledTo', 'isEnabledToTLW', 'isFullScreen', 'isHidden', 'isLeftToRight', 'isMaximized', 'isMinimized', 'isModal', 'isRightToLeft', 'isTopLevel', 'isVisible', 'isVisibleTo', 'isWidgetType', 'isWindow', 'isWindowModified', 'keyPressEvent', 'keyReleaseEvent', 'keyboardGrabber', 'killTimer', 'label', 'label_2', 'label_3', 'languageChange', 'layout', 'layoutDirection', 'leaveEvent', 'locale', 'logicalDpiX', 'logicalDpiY', 'lower', 'mapFrom', 'mapFromGlobal', 'mapFromParent', 'mapTo', 'mapToGlobal', 'mapToParent', 'mask', 'maximumHeight', 'maximumSize', 'maximumWidth', 'metaObject', 'metric', 'minimumHeight', 'minimumSize', 'minimumSizeHint', 'minimumWidth', 'mouseDoubleClickEvent', 'mouseGrabber', 'mouseMoveEvent', 'mousePressEvent', 'mouseReleaseEvent', 'move', 'moveEvent', 'moveToThread', 'mul', 'nativeParentWidget', 'nextInFocusChain', 'normalGeometry', 'num1', 'num2', 'numColors', 'objectName', 'overrideWindowFlags', 'overrideWindowState', 'paintEngine', 'paintEvent', 'paintingActive', 'palette', 'paletteChange', 'parent', 'parentWidget', 'physicalDpiX', 'physicalDpiY', 'pos', 'previousInFocusChain', 'property', 'pyqtConfigure', 'raise_', 'receivers', 'rect', 'releaseKeyboard', 'releaseMouse', 'releaseShortcut', 'removeAction', 'removeEventFilter', 'render', 'repaint', 'res', 'resetInputContext', 'resize', 'resizeEvent', 'restar', 'restoreGeometry', 'result', 'retranslateUi', 'salir', 'saveGeometry', 'scroll', 'sender', 'setAcceptDrops', 'setAccessibleDescription', 'setAccessibleName', 'setAttribute', 'setAutoFillBackground', 'setBackgroundRole', 'setBaseSize', 'setContentsMargins', 'setContextMenuPolicy', 'setCursor', 'setDisabled', 'setEnabled', 'setFixedHeight', 'setFixedSize', 'setFixedWidth', 'setFocus', 'setFocusPolicy', 'setFocusProxy', 'setFont', 'setForegroundRole', 'setGeometry', 'setGraphicsEffect', 'setHidden', 'setInputContext', 'setInputMethodHints', 'setLayout', 'setLayoutDirection', 'setLocale', 'setMask', 'setMaximumHeight', 'setMaximumSize', 'setMaximumWidth', 'setMinimumHeight', 'setMinimumSize', 'setMinimumWidth', 'setMouseTracking', 'setObjectName', 'setPalette', 'setParent', 'setProperty', 'setShortcutAutoRepeat', 'setShortcutEnabled', 'setShown', 'setSizeIncrement', 'setSizePolicy', 'setStatusTip', 'setStyle', 'setStyleSheet', 'setTabOrder', 'setToolTip', 'setUpdatesEnabled', 'setVisible', 'setWhatsThis', 'setWindowFilePath', 'setWindowFlags', 'setWindowIcon', 'setWindowIconText', 'setWindowModality', 'setWindowModified', 'setWindowOpacity', 'setWindowRole', 'setWindowState', 'setWindowTitle', 'setupUi', 'show', 'showEvent', 'showFullScreen', 'showMaximized', 'showMinimized', 'showNormal', 'signalsBlocked', 'size', 'sizeHint', 'sizeIncrement', 'sizePolicy', 'stackUnder', 'startTimer', 'staticMetaObject', 'statusTip', 'style', 'styleSheet', 'sum', 'sumar', 'tabletEvent', 'testAttribute', 'thread', 'timerEvent', 'toolTip', 'topLevelWidget', 'tr', 'trUtf8', 'underMouse', 'ungrabGesture', 'unsetCursor', 'unsetLayoutDirection', 'unsetLocale', 'update', 'updateGeometry', 'updateMicroFocus', 'updatesEnabled', 'visibleRegion', 'whatsThis', 'wheelEvent', 'width', 'widthMM', 'winId', 'window', 'windowActivationChange', 'windowFilePath', 'windowFlags', 'windowIcon', 'windowIconText', 'windowModality', 'windowOpacity', 'windowRole', 'windowState', 'windowTitle', 'windowType', 'x', 'x11Info', 'x11PictureHandle', 'y']

print(dir("s" % (cresult)))

['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

self.num1.text()

Traceback (most recent call last):
  File "calc_fx.py", line 39, in <module>
    ccalc.triggerEvent(self.num1.text(), 2)
NameError: name 'self' is not defined

Este punto es muy raro he tratado de escribir el nombre de muchas formas y no doy con el.

Saludos.

Agregue en el archivo calc_fx.py las siguientes lineas:

print cresult
print cresult.__setattr__

y me devuelve:

<__main__.calc object at 0x7f9c57d32848>
<method-wrapper '__setattr__' of calc object at 0x7f9c57d32848>

No se si servira de algo, esta informacion.

Saludos.

Agrego nueva informacion:

comandos ejecutados y sus respectivas salidas:

print type(cresult)

<class '__main__.calc'>

print cresult.__setattr__

<method-wrapper '__setattr__' of calc object at 0x1e2a848>

print cresult.__dict__

{'num1': <PyQt4.QtGui.QLineEdit object at 0x1e2aa68>, 'num2': <PyQt4.QtGui.QLineEdit object at 0x1e2aaf0>, 'res': <PyQt4.QtGui.QPushButton object at 0x1e2ac88>, 'sum': <PyQt4.QtGui.QPushButton object at 0x1e2ac00>, 'label': <PyQt4.QtGui.QLabel object at 0x1e2a8d0>, 'result': <PyQt4.QtGui.QLineEdit object at 0x1e2ab78>, 'label_2': <PyQt4.QtGui.QLabel object at 0x1e2a958>, 'label_3': <PyQt4.QtGui.QLabel object at 0x1e2a9e0>, 'salir': <PyQt4.QtGui.QPushButton object at 0x1e2ae20>, 'mul': <PyQt4.QtGui.QPushButton object at 0x1e2ad10>, 'div': <PyQt4.QtGui.QPushButton object at 0x1e2ad98>}

print cresult

<__main__.calc object at 0x1e2a848>

print cresult.result

<PyQt4.QtGui.QLineEdit object at 0x1e2ab78>

print cresult.__getattribute__

<method-wrapper '__getattribute__' of calc object at 0x1e2a848>

print getattr(cresult, "result")

<PyQt4.QtGui.QLineEdit object at 0x1e2ab78>

print repr(cresult)

<__main__.calc object at 0x1e2a848>

Claramente el resultado que estoy obteniendo es la direccion de memoria del objeto. Pero he tratado de buscar informacion en Internet, y siempre se hace mencion a que Python no trabaja con punteros y que estos estan ocultos al programador.

Como puedo acceder a la direccion de memoria o al puntero devuelto desde Python ?.

Saludos.

Finalmente descubri algo en internet que puede servir.
Hablan que debes tener multi-threading activado en qt4 o pyqt4.
Como se si esta activado el multi-threading en debian testing amd64 ?.
Si no esta activado, como lo puedo activar ?.

Saludos.

podrías pasar el enlace de lo que leíste para revisarlo?

Linux_mv escribió:

Respecto de tus consultas, las respuestas son:

print(dir(cresult))

['DrawChildren', 'DrawWindowBackground', 'IgnoreMask', 'PaintDeviceMetric', 'PdmDepth', 'PdmDpiX', 'PdmDpiY', 'PdmHeight', 'PdmHeightMM', 'PdmNumColors', 'PdmPhysicalDpiX', 'PdmPhysicalDpiY', 'PdmWidth', 'PdmWidthMM', 'RenderFlag', 'RenderFlags', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'acceptDrops', 'accessibleDescription', 'accessibleName', 'actionEvent', 'actions', 'activateWindow', 'addAction', 'addActions', 'adjustSize', 'autoFillBackground', 'backgroundRole', 'baseSize', 'blockSignals', 'changeEvent', 'childAt', 'childEvent', 'children', 'childrenRect', 'childrenRegion', 'clearFocus', 'clearMask', 'close', 'closeEvent', 'colorCount', 'connect', 'connectNotify', 'contentsMargins', 'contentsRect', 'contextMenuEvent', 'contextMenuPolicy', 'create', 'cursor', 'customContextMenuRequested', 'customEvent', 'deleteLater', 'depth', 'destroy', 'destroyed', 'devType', 'disconnect', 'disconnectNotify', 'div', 'dragEnterEvent', 'dragLeaveEvent', 'dragMoveEvent', 'dropEvent', 'dumpObjectInfo', 'dumpObjectTree', 'dynamicPropertyNames', 'effectiveWinId', 'emit', 'enabledChange', 'ensurePolished', 'enterEvent', 'event', 'eventFilter', 'find', 'findChild', 'findChildren', 'focusInEvent', 'focusNextChild', 'focusNextPrevChild', 'focusOutEvent', 'focusPolicy', 'focusPreviousChild', 'focusProxy', 'focusWidget', 'font', 'fontChange', 'fontInfo', 'fontMetrics', 'foregroundRole', 'frameGeometry', 'frameSize', 'geometry', 'getContentsMargins', 'grabGesture', 'grabKeyboard', 'grabMouse', 'grabShortcut', 'graphicsEffect', 'graphicsProxyWidget', 'handle', 'hasFocus', 'hasMouseTracking', 'height', 'heightForWidth', 'heightMM', 'hide', 'hideEvent', 'inherits', 'inputContext', 'inputMethodEvent', 'inputMethodHints', 'inputMethodQuery', 'insertAction', 'insertActions', 'installEventFilter', 'isActiveWindow', 'isAncestorOf', 'isEnabled', 'isEnabledTo', 'isEnabledToTLW', 'isFullScreen', 'isHidden', 'isLeftToRight', 'isMaximized', 'isMinimized', 'isModal', 'isRightToLeft', 'isTopLevel', 'isVisible', 'isVisibleTo', 'isWidgetType', 'isWindow', 'isWindowModified', 'keyPressEvent', 'keyReleaseEvent', 'keyboardGrabber', 'killTimer', 'label', 'label_2', 'label_3', 'languageChange', 'layout', 'layoutDirection', 'leaveEvent', 'locale', 'logicalDpiX', 'logicalDpiY', 'lower', 'mapFrom', 'mapFromGlobal', 'mapFromParent', 'mapTo', 'mapToGlobal', 'mapToParent', 'mask', 'maximumHeight', 'maximumSize', 'maximumWidth', 'metaObject', 'metric', 'minimumHeight', 'minimumSize', 'minimumSizeHint', 'minimumWidth', 'mouseDoubleClickEvent', 'mouseGrabber', 'mouseMoveEvent', 'mousePressEvent', 'mouseReleaseEvent', 'move', 'moveEvent', 'moveToThread', 'mul', 'nativeParentWidget', 'nextInFocusChain', 'normalGeometry', 'num1', 'num2', 'numColors', 'objectName', 'overrideWindowFlags', 'overrideWindowState', 'paintEngine', 'paintEvent', 'paintingActive', 'palette', 'paletteChange', 'parent', 'parentWidget', 'physicalDpiX', 'physicalDpiY', 'pos', 'previousInFocusChain', 'property', 'pyqtConfigure', 'raise_', 'receivers', 'rect', 'releaseKeyboard', 'releaseMouse', 'releaseShortcut', 'removeAction', 'removeEventFilter', 'render', 'repaint', 'res', 'resetInputContext', 'resize', 'resizeEvent', 'restar', 'restoreGeometry', 'result', 'retranslateUi', 'salir', 'saveGeometry', 'scroll', 'sender', 'setAcceptDrops', 'setAccessibleDescription', 'setAccessibleName', 'setAttribute', 'setAutoFillBackground', 'setBackgroundRole', 'setBaseSize', 'setContentsMargins', 'setContextMenuPolicy', 'setCursor', 'setDisabled', 'setEnabled', 'setFixedHeight', 'setFixedSize', 'setFixedWidth', 'setFocus', 'setFocusPolicy', 'setFocusProxy', 'setFont', 'setForegroundRole', 'setGeometry', 'setGraphicsEffect', 'setHidden', 'setInputContext', 'setInputMethodHints', 'setLayout', 'setLayoutDirection', 'setLocale', 'setMask', 'setMaximumHeight', 'setMaximumSize', 'setMaximumWidth', 'setMinimumHeight', 'setMinimumSize', 'setMinimumWidth', 'setMouseTracking', 'setObjectName', 'setPalette', 'setParent', 'setProperty', 'setShortcutAutoRepeat', 'setShortcutEnabled', 'setShown', 'setSizeIncrement', 'setSizePolicy', 'setStatusTip', 'setStyle', 'setStyleSheet', 'setTabOrder', 'setToolTip', 'setUpdatesEnabled', 'setVisible', 'setWhatsThis', 'setWindowFilePath', 'setWindowFlags', 'setWindowIcon', 'setWindowIconText', 'setWindowModality', 'setWindowModified', 'setWindowOpacity', 'setWindowRole', 'setWindowState', 'setWindowTitle', 'setupUi', 'show', 'showEvent', 'showFullScreen', 'showMaximized', 'showMinimized', 'showNormal', 'signalsBlocked', 'size', 'sizeHint', 'sizeIncrement', 'sizePolicy', 'stackUnder', 'startTimer', 'staticMetaObject', 'statusTip', 'style', 'styleSheet', 'sum', 'sumar', 'tabletEvent', 'testAttribute', 'thread', 'timerEvent', 'toolTip', 'topLevelWidget', 'tr', 'trUtf8', 'underMouse', 'ungrabGesture', 'unsetCursor', 'unsetLayoutDirection', 'unsetLocale', 'update', 'updateGeometry', 'updateMicroFocus', 'updatesEnabled', 'visibleRegion', 'whatsThis', 'wheelEvent', 'width', 'widthMM', 'winId', 'window', 'windowActivationChange', 'windowFilePath', 'windowFlags', 'windowIcon', 'windowIconText', 'windowModality', 'windowOpacity', 'windowRole', 'windowState', 'windowTitle', 'windowType', 'x', 'x11Info', 'x11PictureHandle', 'y']

ese cresult que te devuelve el programa en c es un widget de QT y no un valor, así que por ahí viene el problema, echando un vistazo a sus métodos se ve que hay algunos personalizados como sumar por lo que parece como si el programa en C estuviera devolviendo la ventana entera en cresult.

Linux_mv escribió:

Finalmente descubri algo en internet que puede servir.
Hablan que debes tener multi-threading activado en qt4 o pyqt4.
Como se si esta activado el multi-threading en debian testing amd64 ?.
Si no esta activado, como lo puedo activar ?.

multi-threading? Si el problema sigue siendo el de los primeros post para nada van por ahí los tiros: Wiki
Vamos, que el multi-threading lo podrías usar para ejecutar varias tareas a la vez en el programa y evitar que una tarea larga bloqueara el gui mientras se efectua (ejemplos). O sea, para cosas bastante más complejas que lo que estás haciendo

jjgomera escribió:

ese cresult que te devuelve el programa en c es un widget de QT y no un valor, así que por ahí viene el problema, echando un vistazo a sus métodos se ve que hay algunos personalizados como sumar por lo que parece como si el programa en C estuviera devolviendo la ventana entera en cresult.

Implemente las siguientes funciones y estos son los valores de retorno:
print cresult.sumar.func_code.co_varnames

('cresult',)

print(dir(cresult.sumar.func_code.co_varnames))

['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']

En realidad estuve probando con muchas alternativas, y estas son las que me parecen mas utiles.
Me da la impresion que lo que obtengo es un puntero, de hecho debe ser la direccion de memoria.
El problema es como acceder a la direccion de memoria para sacar el valor que interesa.

Saludos.

Le hice un par de ajustes a los archivos y funcionan mejor.

calc_fx.py

# -*- coding: utf-8 -*-
import sys
from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import *
from calc import Ui_calc
import os
# Python calls a C extension module to register handlers, trigger events
import ccalc
print dir(ccalc)

path = os.path.abspath('')
sys.path.append(path)

class calc(QWidget, Ui_calc):
  def __init__(self):
    QWidget.__init__(self)
    self.setupUi(self)
    self.connect(self.sum, SIGNAL("clicked()"),self.sumar)
    self.connect(self.res, SIGNAL("clicked()"),self.restar)
    #self.connect(self.mul, SIGNAL("clicked()"),self.multiplicar)
    #self.connect(self.div, SIGNAL("clicked()"),self.dividir)

  def sumar(self):
    #ccalc.triggerEvent(float(cres.num1.text()), float(cres.num2.text()))
    ccalc.triggerEvent( float(self.num1.text()), float(self.num2.text()) )
    return self.result.setText('%f' % (self.cresult) )

  def restar(self):
    ccalc.triggerEvent( float(self.num1.text()), float(self.num2.text()) )

   
while False:
  try:
    print "Mensaje de error"
    break
  except ValueError:
    print "ValueError: empty string for float()"
    break

ccalc.setHandler(calc.sumar)
ccalc.triggerEvent(float, float) # simulate events caught by C layer

sys.path.remove(path)

if __name__ == "__main__":
  app = QApplication(sys.argv)
  window = calc()
  window.show()
  sys.exit(app.exec_())

y el archivo ccalc.c

#ifdef __cplusplus
extern "C" {
#endif

#include <Python.h>
#include <stdlib.h>

using namespace std;

/****************************************************************************************/
/* 1) code to route events to Python object note that we could run strings here instead */
/****************************************************************************************/

static PyObject *Handler = NULL;      /* keep Python object in C */

void Route_Event(float cresult) {
    float *cres;
    PyObject *args, *pyres;
    printf("cresult2: %f\n", cresult);
    /* call Python handler */
    /*args = Py_BuildValue("(ii)", num1, num2);   // make arg-list*/
    args = Py_BuildValue("f", cresult);   /* make arg-list */
    //return args;
    printf("args: %f\n", args);
    pyres = PyEval_CallObject(Handler, args);      /* apply: run a call */
    printf("pyres: %f\n", pyres);
    Py_DECREF(args);                              /* add error checks */

    if (pyres != NULL) {
        /* use and decref handler result */
        PyArg_Parse(pyres, "f", &cres);
        printf("%f\n", cres);
        Py_DECREF(pyres);
    }
  }

/*****************************************************************************************************/
/* 2) python extension module to register handlers python imports this module to set handler objects */
/*****************************************************************************************************/

static PyObject* Register_Handler(PyObject *self, PyObject *args) {
    /* save Python callable object */
    Py_XDECREF(Handler);                 /* called before? */
    PyArg_Parse(args, "O", &Handler);    /* one argument? */
    Py_XINCREF(Handler);                 /* add a reference */
    Py_INCREF(Py_None);                  /* return 'None': success */
    return Py_None;
  }

/* let Python simulate event caught by C */
static PyObject* Trigger_Event(PyObject *self, PyObject *args) {
    float num1 = 0, num2 = 0, cresult = 0;
    PyArg_ParseTuple(args,"ff", &num1, &num2); /* carga variables python en punteros de C. */
    cresult = num1 + num2;
    printf("cresult1: %f\n", cresult);
    Route_Event(cresult);
    Py_INCREF(Py_None);
    return Py_None;
  }

static struct PyMethodDef ccalc_methods[] = {
    /*{"setHandler", Register_Handler, METH_VARARGS, "function Register_Handler"},
    {"triggerEvent",  Trigger_Event, METH_VARARGS, "function Trigger_Event"},
    {NULL, NULL, 1, NULL}*/
    {"setHandler", Register_Handler},
    {"triggerEvent",  Trigger_Event, METH_VARARGS},
    {NULL, NULL}
  };

/* this is called by Python on first "import ccalc" */
void initccalc() {
    (void) Py_InitModule("ccalc", ccalc_methods);
  }

#ifdef __cplusplus
}
#endif

El archivo python entrega los valores al archivo C, pero luego desde python no puedo capturar el valor de:
Py_BuildValue("f", cresult);

he probado con ccalc.cresult y tampoco funciona.

Agradezco una pequeña ayuda.

Saludos y Felices fiestas y un feliz 2012.