====== CからPythonのコードを実行する ====== 作成日: 2023-08-05 (土) [[https://youtu.be/w1hjt4I3rbQ|第4回 Python/C APIに触れてみる (3)]] ===== ソースコード ===== ==== toymath.py ==== def add(a, b): return a + b def sub(a, b): return a - b ==== test_toymath.py ==== import toymath x = toymath.add(1, 2) y = toymath.sub(1, 2) x = x + y print(x, y) ==== myapp.c ==== #define PY_SSIZE_T_CLEAN #include 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); } ==== Makefile ==== .PHONY: all all: myapp myapp: myapp.o gcc `python3-config --ldflags --embed` -o $@ $^ myapp.o: myapp.c gcc -c `python3-config --cflags` -o $@ $<