Pythonを使ったC++プログラムの拡張

かなり前にC++からPythonスクリプトを使いたいと思いboost::pythonを調べたことがあった。特にPythonから元のC++のプロセスが持っている関数を呼び出せたら便利だと思っていろいろ調べたのだが、結局やり方がわからなくてそのままになっていた。今日バイト先でこのような状況になり、改めて勉強したところ、やっとやり方がわかった。
具体的には以下のコードの通り。このプログラムを実行すると「2\n3\n」と表示され、C++Pythonのコードがちゃんと連携して動いていることが分かると思う。

#ifndef BOOST_PYTHON_STATIC_LIB
#define BOOST_PYTHON_STATIC_LIB
#endif
#include <iostream>
#include <boost/python.hpp>

using namespace std;

static int testValue = 1;

int getTestValue()
{
	return testValue;
}

BOOST_PYTHON_MODULE( test )
{
	using namespace boost::python;
	def("get_test_value", getTestValue);
}

static const char* CODES =
	"import test\n"
	"print test.get_test_value()\n";

int	main(int argc, char *argv[])
{
	using namespace boost::python;

	try {
		testValue = 2;

		if ( PyImport_AppendInittab("test", inittest) == -1 ) {
			cout << "testモジュールのセットアップに失敗" << endl;
			return 0;
		}

		Py_Initialize();

		object mainModule = import("__main__");
		object global = mainModule.attr("__dict__");

		exec(CODES, global, global);

		testValue = 3;

		exec(CODES, global, global);

	} catch(error_already_set e) {
		cout << "error" << endl;
	}

	return 0;
}

これで苦手な構文解析インタープリターパターンをやらずにすむ・・・。

Boost.Python http://www.boost.org/doc/libs/1_39_0/libs/python/doc/index.html
2008-01-10 - REMINISCENCE//0x http://d.hatena.ne.jp/kikuty/20080110
各種覚え書き: boost::python、embedding(埋め込み) http://wada314.blogspot.com/2008/10/boostpythonembedding.html