拡張モジュール作成 (1)
を参考にWindows版のビルドを試した。
// hello.cpp int add(int x, int y) { return x + y; } void out(const char* adrs, const char* name) { printf("こんにちは、私は %s の %s です。\n", adrs, name); }
// helloWrapper.cpp #include "Python.h" extern int add(int, int); extern void out(const char*, const char*); void _declspec(dllexport) inithello(void); PyObject* hello_add(PyObject* self, PyObject* args) { int x, y, g; if (!PyArg_ParseTuple(args, "ii", &x, &y)) return NULL; g = add(x, y); return Py_BuildValue("i", g); } PyObject* hello_out(PyObject* self, PyObject* args, PyObject* kw) { const char* adrs = NULL; const char* name = NULL; static char* argnames[] = {"adrs", "name", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kw, "|ss", argnames, &adrs, &name)) return NULL; out(adrs, name); return Py_BuildValue(""); } static PyMethodDef hellomethods[] = { {"add", (PyCFunction )hello_add, METH_VARARGS}, {"out", (PyCFunction )hello_out, METH_VARARGS | METH_KEYWORDS}, {NULL}, }; void inithello() { Py_InitModule("hello", hellomethods); }
// hello.def
EXPORTS
inithello
VisualStudioのコマンドプロンプトから以下を実行してビルド。
> cl /LD /IC:/Python27/include hello.c helloWrapper.c C:/Python27/libs/python27.lib hello.def > move hello.dll hello.pyd
あとは、普通にimport helloして使える。