vendredi 14 juillet 2017

Extract C++ base class from Python derived object

I am deriving a class in python based on a C++ class. I want to create an instance of the python class and then extract a Card* pointer. But I get a type error saying "No registered converter was able to extract a C++ pointer to type class Card from this Python object of type Fire_Spirit."

Base C++ class constructor

Card(string name, string text);

Boost.Python Wrapper

BOOST_PYTHON_MODULE(Card)
{
    using namespace boost::python;
    class_<Card>("Card", init<string, string>());
}

Derived Python class

from Card import *

class Fire_Spirit(Card):
    def __init__(self, name="Fire Spirit", text="A thing"):
        self.name = name
        self.text = text
        super(Fire_Spirit, self).__init__(name, text)

Extraction code

using namespace boost::python;
Py_Initialize();

// Get a C++ pointer of the derived python class.
object derived = import("Cards.Fire_Spirit").attr("Fire_Spirit");
object class_instance = derived();
Card* card = extract< Card* >(class_instance);

Py_Finalize();

Aucun commentaire:

Enregistrer un commentaire