【问题标题】:Luabind setting property of derived type with base type派生类型的 Luabind 设置属性与基类型
【发布时间】:2014-06-27 22:11:38
【问题描述】:

我正在使用 LuaBind 将 c++ 类公开给 Lua 脚本。我遇到了无法将基类转换为其派生类的问题。我有一个返回基类型对象的工厂类。我试图用这些对象设置一些从基类型派生的类型的字段。我已经将我的问题归结为一些测试代码,可以重现问题并更清楚地解释它。

c++ 类定义

class Base {
public:
  virtual void say() { cout << "a" << endl; }
};

class Derived : public Base {
public:
  virtual void say() { cout << "b" << endl; }
};

class TestClass {
public:
  Base *GetBase() { return (Base *)new Derived(); }
  Derived *derivedRef;
};

c++ LuaBind绑定代码

module(L)[
    class_<Base>("Base")
    .def(constructor<>())
    .def("say", &Base::say)];

module(L)[class_<Derived, Base>("Derived")
    .def(constructor<>())
    .def("say", &Derived::say)];

module(L)[class_<TestClass>("TestClass")
    .def(constructor<>())
    .def("GetBase", &TestClass::GetBase)
    .def_readwrite("derivedRef", &TestClass::derivedRef)];

Lua 代码

testClass = TestClass()
base = testClass:GetBase()
testClass.derivedRef = base

错误

 occurred executing a LUA script: No matching overload found, candidates: 
 void <unknown>(TestClass&,Derived* const&)

有谁知道在 LuaBind 中是否可以向上转换,如果可以,我应该怎么做?

【问题讨论】:

    标签: c++ binding casting lua luabind


    【解决方案1】:

    经过漫长的过程,我解决了这个问题。

    首先我读到here,我正在运行的 LuaBind 版本 (0.9) 应该支持在传递到参数时自动向下/向上转换类型。这表明这是可能的。

    然后我发现here 有一个特殊的标头用于转换共享指针(我意识到我正在使用它)。 LuaBind 附带的转换器仅适用于 boost 共享指针。获取 source for the boost smart pointer converter 并将 boost:: 的每个实例替换为 std:: 并生成 a few small modifications 非常简单,因此它可以编译。

    然后我开始收到错误提示

    std::runtime_error: 'Trying to use unregistered class'
    

    当我调用绑定方法时。

    有一个共享指针转换器的版本here,但它没有在我的机器上编译。我用它作为参考来制作另一个header file,它允许 LuaBind 绑定来自标准库的共享指针。

    长话短说,包括以下两个文件,并且当您使用标准库版本而不是 boost 版本时,共享指针的自动向上/向下转换工作。

    我正在使用带有 clang 编译器的 Xcode 5,我还没有使用其他编译器对其进行测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-08
      • 1970-01-01
      • 2015-04-09
      • 2018-07-31
      • 1970-01-01
      • 2016-06-02
      • 2014-03-22
      相关资源
      最近更新 更多