を1はC++からPythonのを呼び出す必要がある、とC++は、主な機能を所有しているときは、その一つがはパイソン埋め込む必要がありますC++プログラム内のインタラプタ。 Boost.Python APIはPython/C APIの包括的なラッパーではないので、Python/C APIの一部を直接呼び出す必要があるかもしれません。それにもかかわらず、Boost.PythonのAPIは相互運用性を向上させます。詳細については、公式のBoost.Python embedding tutorialを読むことを検討してください。ここ
は、Pythonを埋め込むC++プログラムの基本骨格である:パイソンを埋め込む場合
int main()
{
// Initialize Python.
Py_Initialize();
namespace python = boost::python;
try
{
... Boost.Python calls ...
}
catch (const python::error_already_set&)
{
PyErr_Print();
return 1;
}
// Do not call Py_Finalize() with Boost.Python.
}
は、モジュールは、カスタムの場所からインポートすることができるようにPYTHONPATH
介しmodule search pathを増強する必要があるかもしれません。
// Allow Python to load modules from the current directory.
setenv("PYTHONPATH", ".", 1);
// Initialize Python.
Py_Initialize();
多くの場合、Boost.Python APIはPython-ishの方法でC++コードを書く方法を提供します。
含ま
MyPythonClass
モジュール考える
#include <boost/python.hpp>
#include <cstdlib> // setenv
int main()
{
// Allow Python to load modules from the current directory.
setenv("PYTHONPATH", ".", 1);
// Initialize Python.
Py_Initialize();
namespace python = boost::python;
try
{
// >>> import MyPythonClass
python::object my_python_class_module = python::import("MyPythonClass");
// >>> dog = MyPythonClass.Dog()
python::object dog = my_python_class_module.attr("Dog")();
// >>> dog.bark("woof");
dog.attr("bark")("woof");
}
catch (const python::error_already_set&)
{
PyErr_Print();
return 1;
}
// Do not call Py_Finalize() with Boost.Python.
}
:C++でPythonインタプリタを埋め込み、及びCは、ディスクからMyPythonClass
PythonモジュールをインポートMyPythonClass.Dog
のインスタンスをインスタンス化し、その後Dog
インスタンスにbark()
を呼び出す++有する次の例demonstrates :
class Dog():
def bark(self, message):
print "The dog barks: {}".format(message)
上記プログラム出力:
The dog barks: woof
Bigありがとうございます。ワーキング!!! –
最後に 'Py_Finalize();'を呼んではいけませんか? –
@TrevorHickey、no。 [Boost.Pythonの埋め込みドキュメント](http://www.boost.org/doc/libs/1_65_1/libs/python/doc/html/tutorial/tutorial/embedding.html)に記載されているように、Py_Finalize()通訳を止めるために呼び出されるべきではありません。 –