컴퓨터/linux2011. 3. 29. 00:04
아래 내용은 맨 아래 출처의 저자님의 포스팅을 제가 했던 상황에 맞게 조금 바꾸었습니다.
(이상하게 트랙백이 안걸리네요. )

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

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

swig은 안깔려있는 경우가 있어서 sudo apt-get install swig을 깔아줍니다. 


~/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 -fPIC sample.c sample_wrap.c -I/usr/include/python2.4 
(운영체제가 X86_64인 경우 저 붉은 색으로 되는 부분을 옵션으로 해줘야합니다.) 
(또한 바로 하면 Python.h 파일을 못찻기때문에 꼭 python-dev를 설치 하셔야 합니다.) 

~/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

ㅇㅋ!

(마지막 부분은 꼭 ipython을 쓰지 않아도 잘 작동 하였습니다. )


출처 : http://cybershin.x-y.net/tt/entry/swig
 
Posted by blindfish