さて、ここでは、以下の 2 つのことについて言及しています。
- Python内でc関数を呼び出す方法(Pythonの拡張)
- CプログラムからPython関数/スクリプトを呼び出す方法(Embedding Python)
#2の「Pythonの埋め込み」
以下のコード セグメントを使用できます。
#include "python.h"
int main(int argc, char *argv[]) {
Py_SetProgramName(argv[0]); /* optional but recommended */
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
"print 'Today is',ctime(time())\n");
/*Or if you want to run python file within from the C code*/
//pyRun_SimpleFile("Filename");
Py_Finalize();
return 0; }
#1の「拡張Python」の
場合、Ctypesを使用するのが最善の策です(ところで、Pythonのすべてのバリアントで移植可能です)。
ctypesインポートから *
libc = cdll.msvcrt
libc.time を印刷する (なし)
1438069008
printf = libc.printf
printf("こんにちは、%s\n", "ワールド!")
こんにちは世界!14
printf("%d 本のビール\n", 42)
ビール42本 19本
詳細なガイドについては、私のブログ記事を参照してください。