/var/log/soymsk

id:soy_msk


C++からPythonモジュールを使う

C++ からPythonモジュールを使うのをやってみた。
id:Wackyさんの記事を参考にhttp://www.linuxjournal.com/article/8497からサンプルをそのまま流用。

まずPythonモジュールから。

def hello():
	print "Hello, Python!";
	return "Success";

続いてC++

#include <iostream>
#include <cstdio>
#include "python2.6/Python.h"
using namespace std;
void pyWraper() {
	FILE * exp_file;
	PyObject *module, *global_dict, *expression, *result;
	const char *exp = "pymodule.py";
	const char* func_name = "hello";

	exp_file = fopen(exp, "r");
	PyRun_SimpleFile(exp_file, exp);
	module = PyImport_AddModule("__main__");
	global_dict = PyModule_GetDict(module);

	expression = PyDict_GetItemString(global_dict, func_name);
	result = PyObject_CallObject(expression, NULL);
	if(PyString_Check(result)) cout << PyString_AsString(result) << endl;
}


int main() {
	Py_Initialize();
	pyWraper();
	Py_Finalize();
}

[出力]
Hello Python!
Success

もちろん引数を渡すこともできる。