6

我的朋友有一个C用 Linux 编写的带有 GUI的应用程序GTK。现在我们想用python(wxpythonPyQT)重写GUI。

我没有使用 Python 的经验,也不知道如何让 Python 与 C 进行通信。我想知道这是否可行,如果可以,我应该如何实现它?

4

3 回答 3

5

是的,它可以从 Python 调用“C”函数。

请查看 SWIG(已弃用),Python 也提供了自己的可扩展性 API。你可能想调查一下。

还有谷歌 CTypes。

链接:

Python 扩展

一个简单的例子:为此,我在 Windows 上使用了 Cygwin。我在这台机器上的 python 版本是 2.6.8 - 使用 test.py 加载名为“myext.dll”的模块对其进行了测试 - 它工作正常。您可能需要修改Makefile以使其在您的机器上工作。

原版.h

#ifndef _ORIGINAL_H_
#define _ORIGINAL_H_

int _original_print(const char *data);

#endif /*_ORIGINAL_H_*/

原版.c

#include <stdio.h>
#include "original.h"

int _original_print(const char *data)
{
  return printf("o: %s",data);
}

存根.c

#include <Python.h>
#include "original.h"

static PyObject *myext_print(PyObject *, PyObject *);

static PyMethodDef Methods[] = {
  {"printx", myext_print, METH_VARARGS,"Print"},
  {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC initmyext(void)
{
  PyObject *m;
  m = Py_InitModule("myext",Methods);
}

static PyObject *myext_print(PyObject *self, PyObject *args)
{
  const char *data;
  int no_chars_printed;
  if(!PyArg_ParseTuple(args, "s", &data)){
      return NULL;
  }
    no_chars_printed = _original_print(data);
    return Py_BuildValue("i",no_chars_printed);  
}

生成文件

PYTHON_INCLUDE = -I/usr/include/python2.6
PYTHON_LIB = -lpython2.6
USER_LIBRARY = -L/usr/lib
GCC = gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -DMAJOR_VERSION=1 -DMINOR_VERSION=0 -I/usr/include -I/usr/include/python2.6 

win32 : myext.o
    - gcc -shared myext.o $(USER_LIBRARY) $(PYTHON_LIB) -o myext.dll

linux : myext.o
    - gcc -shared myext.o $(USER_LIBRARY) $(PYTHON_LIB) -o myext.so

myext.o: stub.o original.o
    - ld -r stub.o original.o -o myext.o

stub.o: stub.c
    - $(GCC) -c stub.c -o stub.o

original.o: original.c
    - $(GCC) -c original.c -o original.o

clean: myext.o
    - rm stub.o original.o stub.c~ original.c~ Makefile~

测试.py

import myext
myext.printx('hello world')

输出

o:你好世界

于 2012-11-01T07:55:10.133 回答
2

抱歉,我没有 Python 经验,所以不知道如何让 Python 与 C 程序通信。

是的,这正是你的做法。将您的 C 代码转换为 Python 模块,然后您就可以用 Python 编写整个 GUI。请参阅扩展和嵌入 Python 解释器

于 2012-11-01T07:55:18.600 回答
0

If you have an option between C or C#(Sharp) then go with C# and use visual studio, you can build the GUI by dragging and dropping components easy. If you want to do something in python look up wxPython. Java has a built in GUI builder known as swing. You'll need some tutorials, but unless this program doesn't need to be portable just go with C# and build it in 10 minutes .

Also, you can write your code in C and export it as a python module which you can load from python. It`s not very complicated to set up some C functions and have a python GUI which calls them. To achieve this you can use SWIG, Pyrex, BOOST.

于 2012-11-01T11:22:52.590 回答