Python/요리 방법
Cython 간단한 예제
DWGoon
2015. 2. 28. 14:03
참조: "Learning Cython Programming" by Philip Herron (2013, Packt Publishing)
*운영체제: Windows7 (64bit)
*컴파일러: gcc (tdm64-2) 4.8.1
*파이썬: Python 2.7.7 |Anaconda 2.0.1 (64-bit)|
[주의!] Windows7 64bit 용 Anaconda Python 배포판 2.7 버전은 Microsoft Visual Studio 2008 (MSVC 2008)에서 컴파일됐기 때문에, TDM-GCC 사용 시 문제가 많을 수 있습니다. 이 예제는 TDM-GCC를 사용했지만, 실제 Cython을 이용하여 프로그램을 작성하실 분들은 반드시 MSVC 2008을 사용하기를 권합니다. 제 경험으로는 TDM-GCC로 컴파일한 Cython 프로그램을 MSVC로 컴파일한 Python으로 실행할 경우 런타임 에러가 나면서 죽는 경우가 있었습니다 (황당하게도, 어느 때에는 죽지 않고 실행되기도 합니다).
<source-code: mycode.c>
#include <stdio.h>
int myfunc (int a, int b)
{
printf ("look we are within your c code!!\n");
return a + b;
}
int myfunc (int a, int b)
{
printf ("look we are within your c code!!\n");
return a + b;
}
</source-code>
<source-code: mycode.h>
#ifndef __MYCODE_H__
#define __MYCODE_H__
extern int myfunc (int, int);
#endif //__MYCODE_H__
#define __MYCODE_H__
extern int myfunc (int, int);
#endif //__MYCODE_H__
</source-code>
<source-code: mycodecpy.pyx>
cdef extern from "mycode.h":
cdef int myfunc (int, int)
cdef int myfunc (int, int)
def callCfunc ():
print myfunc (1,2)
</source-code>
커맨드 창에서 아래와 같이 입력
<컴파일>
gcc (tdm64-2) 4.8.1을 사용했는데, 윈도우에서 컴파일 할 때 -D MS_WIN64 옵션을 지정해 주어야 링크할 때 undefined refrence 에러가 발생하지 않는다. 옵션을 지정해 주지 않으면
$ gcc -D MS_WIN64 -g -O2 -fpic -c mycode.c -o mycode.o -Ic:\Anaconda\include
$ gcc -D MS_WIN64 -g -O2 -fpic -c mycodecpy.c -o mycodecpy.o -Ic:\Anaconda\include
<링크>
DLL 파일(리눅스에서는 *.so)의 확장자명을 "mycodecpy.dll"와 같이 지정하면 python에서 import가 안 된다 (왜 그럴까..?). "*.pyd"로 지정해야 import가 된다.
$ gcc -shared -O -Wall -D MS_WIN64 -o mycodecpy.pyd mycode.o mycodecpy.o -L"c:\Anaconda\libs" -lpython27
<실행>
$ python
Python 2.7.7 |Anaconda 2.0.1 (64-bit)| (default, Jun 11 2014, 10:40:02) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://binstar.org
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://binstar.org
>>> import mycodecpy # 책에는 "mycodepy" 라고 써있다 (c가 빠진 erratum 이다).
>>> mycodecpy.callCfunc()
look we are within your c code!
3
>>> mycodecpy.callCfunc()
look we are within your c code!
3