"AttributeError: 'module' has no attribute 'player'" when attempting to load python object into C++ with Boost::Python

"AttributeError: 'module' has no attribute 'player'" when attempting to load python object into C++ with Boost::Python

终端错误如下:

AttributeError: 'module' has no attribute 'player'

Python 文件:character_py.py

import sys
sys.path.append('./character')
import character

player = character.Character('!',0,0)

和 C++ 文件:Character.cpp

#include "../inc/Character.hpp"
#include <ncurses.h>
#include <boost/python.hpp>

using namespace boost::python;

BOOST_PYTHON_MODULE(character)
{
  class_<Character>("Character", init<char, int, int>())
    .def("Position", &Character::Position)
    .def("GetRow", &Character::GetRow)
    .def("GetCol", &Character::GetCol)
    .def("GetSymbol", &Character::GetSymbol)
    .def("SetRow", &Character::SetRow)
    .def("SetCol", &Character::SetCol)
    .def("SetSymbol", &Character::SetSymbol)
    ;
}

Character::Character(char s, int r, int c) 
{
  symbol = s;
  row = r;
  col = c;

  Initialize();
}

void Character::Initialize()
{
  object character_m = import("character_py");
  object player = character_m.attr("player");
}

几天来我一直在研究这个问题,但我似乎无法从我创建的 python 模块中找出实际对象的加载。我可以导入它就好了。我可以从 C++ 执行 python 代码。但是我无法从脚本中获取这些数据。我尝试使用字典:

object character_dict = character_m.attr("__dict__");
object player = character_dict["player"];

但是我每次都得到同样的错误。

任何帮助将不胜感激,因为在解决这个特定问题之前我基本上处于死胡同。

此代码无法运行。您正试图在创建对象的过程中获取该对象的实例。

将其放入 C++ 中(代码导致无限递归):

struct Character;

Character get_character();

struct Character
{
    Character()
    {
        Initialize();
    }

    void Initialize()
    {
        Character c = get_character();
    }
};

Character get_character() { return Character(); }

int main()
{
    Character c;

    return 0;
}

为了使您的代码正常工作,您必须在 Character 构造函数/Character 构造函数中调用的函数之外的其他地方执行 python 代码。