5

Boost-Python を使用して Python の Enum をラップする際に問題があります。

最初は、 try-catch (以下にコード全体を挿入しました) ステートメントで次のようなことをするつもりでした:

main_namespace["Motion"] = enum_<TestClass::Motion>("Motion")
    .value("walk", TestClass::walk)
    .value("bike", TestClass::bike)
;

すべてが順調で、コンパイルが完了しました。実行時にこのエラーが発生しました(これは意味がありません):

AttributeError: 'NoneType' object has no attribute 'Motion'

その後、コードで BOOST_PYTHON_MODULE を使用して Python モジュールを作成することにしました。Python インタープリターを初期化した後、このモジュールをすぐに使用したかったのですが、方法がわかりませんでした (?)。以下は私のコード全体です:

#include <boost/python.hpp>
#include <iostream>

using namespace std;
using namespace boost::python;

BOOST_PYTHON_MODULE(test)
{
    enum_<TestClass::Motion>("Motion")
        .value("walk", TestClass::walk)
        .value("bike", TestClass::bike)
    ;
}

int main()
{
    Py_Initialize();

    try
    {    
        object pyMainModule = import("__main__");
        object main_namespace = pyMainModule.attr("__dict__");

        //What previously I intended to do
        //main_namespace["Motion"] = enum_<TestClass::Motion>("Motion")
        //  .value("walk", TestClass::walk)
        //  .value("bike", TestClass::bike)
        //;

        //I want to use my enum here
        //I need something like line below which makes me able to use the enum!

        exec("print 'hello world'", main_namespace, main_namespace);
    }
    catch(error_already_set const&)
    {
        PyErr_Print();
    }

    Py_Finalize();
    return 0;
}

Python での Enum のラッピングと使用について知っておくと便利なことは何でも歓迎します! 前もって感謝します

4

1 に答える 1