HYPER MIKAN BOX
検索
最近の変更
メディアマネージャー
サイトマップ
文書の表示
以前のリビジョン
バックリンク
ログイン
トレース:
この文書は読取専用です。文書のソースを閲覧することは可能ですが、変更はできません。もし変更したい場合は管理者に連絡してください。
====== CからPythonのコードを実行する ====== 作成日: 2023-08-05 (土) [[https://youtu.be/w1hjt4I3rbQ|第4回 Python/C APIに触れてみる (3)]] ===== ソースコード ===== ==== toymath.py ==== <file python> def add(a, b): return a + b def sub(a, b): return a - b </file> ==== test_toymath.py ==== <file python> import toymath x = toymath.add(1, 2) y = toymath.sub(1, 2) x = x + y print(x, y) </file> ==== myapp.c ==== <file c> #define PY_SSIZE_T_CLEAN #include <Python.h> int main() { Py_Initialize(); PyRun_SimpleString("import os, sys \n" "sys.path.append(os.getcwd()) \n"); FILE *fp = fopen("test_toymath.py", "r"); if (fp == NULL) { fprintf(stderr, "Error: cannot open file.\n"); exit(1); } PyRun_SimpleFile(fp, "test_toymath.py"); fclose(fp); } </file> ==== Makefile ==== <file makefile> .PHONY: all all: myapp myapp: myapp.o gcc `python3-config --ldflags --embed` -o $@ $^ myapp.o: myapp.c gcc -c `python3-config --cflags` -o $@ $< </file>
文書の先頭へ