ユーザ用ツール

サイト用ツール


youtube:python-mixing-004

差分

このページの2つのバージョン間の差分を表示します。

この比較画面へのリンク

両方とも前のリビジョン前のリビジョン
youtube:python-mixing-004 [2024/02/28 18:26] – 削除 - 外部編集 (不明な日付) 127.0.0.1youtube:python-mixing-004 [2024/02/28 18:26] (現在) – ↷ toybox:python-mixing-004 から youtube:python-mixing-004 へページを移動しました。 freemikan
行 1: 行 1:
 +====== 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>

特に明示されていない限り、本Wikiの内容は次のライセンスに従います: CC0 1.0 Universal
CC0 1.0 Universal Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki