拡張モジュール作成 (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して使える。

Pythonの組み込み

今さらながら、C++Pythonを簡単に組み込めることに気がついた。


Pythonでexecfile('hoge.py')を呼び出すだけのexeを作成し、C++側では、exeを実行するだけで良い。
もちろん、もっと汎用化したければ、hoge.pyを引数のパラメータで、変更出来るようにしたり、SWIGなどと連携させて、C++と直接、値の受け取りを行えるようにしても良い。


exeをコマンドプロンプト表示しないようにして、起動すればPythonが実行されていることすら気付かない。

PythonのReportLabのソースをpy2exeでexe化する際のメモ

setup.pyのsetup()のoptionsでpackagesを指定する必要がある。

# coding: cp932
# setup.py
from distutils.core import setup
import py2exe

packages=[
	'reportlab',
	'reportlab.graphics.charts',
	'reportlab.graphics.samples',
	'reportlab.graphics.widgets',
	'reportlab.graphics.barcode',
	'reportlab.graphics',
	'reportlab.lib',
	'reportlab.pdfbase',
	'reportlab.pdfgen',
	'reportlab.platypus',]
	
py2exe_options = {
  "compressed": 1,
  "optimize": 2,
  "bundle_files": 1,
  "packages": packages}

setup(
  options = {"py2exe": py2exe_options},
  console = [
    {"script" : "hoge.py"}],
  zipfile = None)

Tython


Tythonは、XBOXKinectを利用したインターフェース。これは非常に面白い。将来的には、OSもこのようなインターフェースになると思うが、自作プリポストにもぜひ取り入れたい。