BLOG ARTICLE 연동 | 1 ARTICLE FOUND

  1. 2008.04.01 python과 C 연동하기

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