BLOG ARTICLE SWIG | 2 ARTICLE FOUND

  1. 2008.10.27 python과 C 연동하기 #2 - GTK 붙여보기 1
  2. 2008.04.01 python과 C 연동하기

예전에 정리한 바와 같이 python은 C와 연동하기 나름 쉽습니다.

이번에는 마치 pyGtk처럼 다른 큰 library들을 끼고도 잘 되나 실험해봤습니다.

interface와 몸통파일은 다음과 같습니다.

>> cat foo.i
 %module foo
 %{
 extern int foo(void);
 %}
 extern int foo(void);

>> cat foo.c
#include <gtk/gtk.h>
int foo(void) {
    gtk_init(0,0);   
    GtkWidget *window;   
    window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
    gtk_window_set_title (GTK_WINDOW (window), "foo" );
    gtk_widget_show (window);
    gtk_main ();

    return 0;
}


그리고 다음과 같이 연결을 해주면 됩니다.

dsp@dsplinux:~/Projects/swig$ swig -python foo.i
dsp@dsplinux:~/Projects/swig$ gcc -c foo.c foo_wrap.c -I/usr/include/python2.5 `pkg-config --cflags gtk+-2.0`
dsp@dsplinux:~/Projects/swig$ ld -shared foo.o foo_wrap.o -o _foo.so `pkg-config --libs gtk+-2.0`

dsp@dsplinux:~/Projects/swig$ ipython
Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
Type "copyright", "credits" or "license" for more information.

IPython 0.8.1 -- An enhanced Interactive Python.
?       -> Introduction to IPython's features.
%magic  -> Information about IPython's 'magic' % functions.
help    -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.

In [1]: import foo

In [2]: foo.foo()

위와 같이 foo.foo()를 실행하면 윈도가 잘 뜨는 것을 확인할 수 있습니다.
정말로 pyGtk처럼 하려면 c++스타일로 붙이면 되겠죠.

AND

python을 쓰다보면 C와 연동할 일이 생기는데,
이럴 때 사용하게 되는 것이 swig입니다.
http://www.swig.org/

다음은 초간단한 c 함수를 만들어서 swig를 이용하여,
python에서 호출을 해 보도록 하겠습니다.
( 이 내용들은 swig tutorial에 있는 내용들을 좀 더 간단하게
제 환경에서 테스트해본 결과입니다. )

~/temp$ vi sample.c
int inc( int a ){
        return a+1;
}

~/temp$ vi sample.i
%module sample
%{
extern int inc(int a);
%}
extern int inc(int a);

~/temp$ swig -python sample.i
~/temp$ gcc -c sample.c sample_wrap.c -I/usr/include/python2.4
~/temp$ ld -shared sample.o sample_wrap.o -o _sample.so

~/temp$ ipython
Python 2.4.3 (#2, Oct  6 2006, 07:52:30)
Type "copyright", "credits" or "license" for more information.

IPython 0.7.1.fix1 -- An enhanced Interactive Python.
?       -> Introduction to IPython's features.
%magic  -> Information about IPython's 'magic' % functions.
help    -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.

In [1]: import sample
In [2]: sample.inc(1)
Out[2]: 2

ㅇㅋ!

AND