C言語でPythonのモジュールを自作する

C言語Pythonのモジュールを自作する方法を書く。

環境

参考にしたサイト

1. 準備(virtualenvで実験用環境を作る)

virtualenvコマンドを使って、実験用の環境を作る。virtualenvコマンドを使うとシステムのPython環境と分離した環境が作れる。

まず、virtualenvをインストール。

$ sudo apt install virtualenv

次に、実験用環境mypylibを作って、activateする。 (activateするとプロンプトに(ディレクトリ名)が付く。元の環境に戻るためには$ deactivateを実行。)

$ mkdir mypylib
$ virtualenv --no-site-packages mypylib
$ source mypylib/bin/activate

2. 自作モジュールのC言語ソースを書く

自作モジュールのC言語ソースmypylib/spammodule.cは以下。

#include <Python.h>

static PyObject *
spam_system(PyObject *self, PyObject *args)
{
  const char *command;
  int sts;

  if (!PyArg_ParseTuple(args, "s", &command))
    return NULL;

  sts = system(command);
  return Py_BuildValue("i", sts);
}

static PyMethodDef SpamMethods[] = {
  {"system", spam_system, METH_VARARGS, "Execute a shell command."},
  {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC
initspam(void)
{
  (void) Py_InitModule("spam", SpamMethods);
}

3. .whlファイル作成用のsetup.pyを用意

.whlファイルを作成するためのmypylib/setup.pyは以下。

from setuptools import setup, Extension

setup(
    name='spam',
    ext_modules=[Extension('spam', sources=['spammodule.c'])]
    )

4. .whlファイル作成

以下のコマンドで.whlファイルを作成する。

(mypylib)$ python setup.py bdist_wheel

mypylib/dist/spam-0.0.0-cp27-cp27mu-linux_x86_64.whlが出来上がる。

5. .whlのインストールと動作確認

作った.whlファイルを実験用環境にインストールする。

(mypylib)$ pip install dist/spam-0.0.0-cp27-cp27mu-linux_x86_64.whl

動作確認。

$ python
Python 2.7.15rc1 (default, Nov 12 2018, 14:31:15) 
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import spam
>>> status = spam.system("ls -l")