Embedding Python in C/C++: Part I
살다보면 C언어에서 Python을 사용할 일이 있을 겁니다. :)
파이선 라이브러리를 받아서 설정 하는 일련의 작업들은 모두 스킵하고...
(간단히 언급하면, python의 include, lib폴더를 각각 추가해주고 #include<phthon.h> 하면 끝)
[2]에 따르면, 아래와 같이 처리를 안해주면 Visual C++ 에서 인식하지 못할 때가있다고 합니다.
(직접 해보지 않아서 잘 모르겟음)
#include <python.h> |
#ifdef _DEBUG #undef _DEBUG #include <python.h> #define _DEBUG #else #include <python.h> #endif |
1. simple 소스 (no parameters)
> 아래의 코드는 Python 모듈의 함수를 호출하는 코드입니다.
call_function.c |
// call_function.c - A sample of calling // python functions from C code #include <Python.h> int main(int argc, char *argv[]) { PyObject *pName, *pModule, *pDict, *pFunc, *pValue; if (argc < 3) { printf("Usage: exe_name python_source function_name\n"); return 1; } // Initialize the Python Interpreter Py_Initialize(); // Build the name object pName = PyString_FromString(argv[1]); // Load the module object pModule = PyImport_Import(pName); // pDict is a borrowed reference pDict = PyModule_GetDict(pModule); // pFunc is also a borrowed reference pFunc = PyDict_GetItemString(pDict, argv[2]); if (PyCallable_Check(pFunc)) { PyObject_CallObject(pFunc, NULL); } else { PyErr_Print(); } // Clean up Py_DECREF(pModule); Py_DECREF(pName); // Finish the Python Interpreter Py_Finalize(); return 0; } |
간략히 주석으로 설명이 되어 있어 이해하기는 크게 어렵지 않습니다.
물론 각 파이썬 함수들의 기능은 홈페이지[3]를 참고 해야겠지요. (http://docs.python.org/)
그러나 짚고 넘어가야 할 것이 있습니다.
- python에서는 모든 것이 객체이다.
- pDict와 pFunc는 'borrowed reference' 이라는데, 참조 개념이 들어가서 참조 카운트를 자동으로 관리해 주나 봅니다. 따라서 Py_DECREF를 호출하지 않아도 됩니다.
- Py_xxxx로 시작하는 모든 함수들은 Python/C API 이구요
- 위 코드는 파이선을 지원하기만 하면, 모든 플랫폼에서 컴파일 및 실행이 되네요 ~
그리고 아래는 include 할 python 파일(.py)
Py_function.py |
''' py_function.py - Python source designed to ''' <-- 이건 주석 ''' demonstrate the use of python embedding''' def multiply(): c = 12345*6789 print 'The result of 12345 x 6789 :', c return c |
(참고로, 맨 처음 파이선 접할때 고생했던게 바로 '탭 문자' 였습니다,
C/C++ 같은 경우는 소스를 보기 좋게 하기 위해서, 탭을 사용하는데 반면,
python은 언어 차원에서 문법으로 정해 놓았기 때문에, 문법에 맞춰 코딩을 하면 자연스레 보기 좋습니다)
그리고 위의 코드를 컴파일 한 후에 아래처럼 실행하면 됩니다
실행 (command line에서 입력) |
|
py_function : 파이선 파일 이름
multiply : 파이선 내의 함수 이름
2. Parameters 넘기기
python 함수에 파라미터를 넘겨야 할 필요도 있지요..
글이 길어서 다음 페이지로 넘겨야겠네요...
* 참조 :
1. http://www.codeproject.com/KB/cpp/embedpython_1.aspx
2. http://mc787.egloos.com/648184
3. http://python.org/