如何将原始指针与Luabind绑定

时间:2014-12-04 21:02:27

标签: c++ pointers lua box2d luabind

我试图使用luabind绑定box2d,以便我可以在我的lua脚本中使用它。我遇到了一个问题,我似乎无法用luabind绑定原始指针。以下是我的代码:

luabind::module(luaState)[
   luabind::class_<b2Shape>("b2Shape")
];

luabind::module(luaState)[
    luabind::class_<b2PolygonShape, luabind::bases<b2Shape>>("b2PolygonShape")
    .def(luabind::constructor<>())
    .def("GetChildCount", &b2PolygonShape::GetChildCount)
    .def("SetAsBox", (void (b2PolygonShape::*) (float32 hx, float32 hy) ) &b2PolygonShape::SetAsBox)
    .def("SetAsBox", (void (b2PolygonShape::*) (float32 hx, float32 hy, const b2Vec2& center, float32 angle) ) &b2PolygonShape::SetAsBox)
    .def("TestPoint", (void (b2PolygonShape::*) (const b2Transform& transform, const b2Vec2& p) ) &b2PolygonShape::TestPoint)
    .def("ComputeAABB", (void (b2PolygonShape::*) (b2AABB* aabb, const b2Transform& transform, int32 childIndex) ) &b2PolygonShape::ComputeAABB)
    .def("GetVertexCount", (void (b2PolygonShape::*) () ) &b2PolygonShape::GetVertexCount)
    .def("GetVertex", (const b2Vec2& (b2PolygonShape::*) (int32 index) ) &b2PolygonShape::GetVertexCount)
    .def("Validate", &b2PolygonShape::Validate)
];

luabind::module(luaState)[
    luabind::class_<b2FixtureDef>("b2FixtureDef")
    .def(luabind::constructor<>())
    .def_readwrite("shape", &b2FixtureDef::shape)
    .def_readwrite("friction", &b2FixtureDef::friction)
    .def_readwrite("restitution", &b2FixtureDef::restitution)
    .def_readwrite("density", &b2FixtureDef::density)
    .def_readwrite("isSensor", &b2FixtureDef::isSensor)
    .def_readwrite("filter", &b2FixtureDef::filter)
];

这是我的lua代码:

local anchorBodyDef = b2BodyDef()
anchorBodyDef.position = b2Vec2(20.0, 0.0)

local anchorShape = b2PolygonShape()
anchorShape:SetAsBox(2.0, 0.5)

local anchorFixDef = b2FixtureDef()
anchorFixDef.shape = anchorShape

每当我尝试使用anchorFixDef.shape = anchorShape为我的fixtureDef指定一个形状时,lua会抛出一个错误:

terminate called after throwing an instance of 'luabind::error'
what():  lua runtime error

你会如何在luaBind中绑定像const b2Shape* shape;这样的东西,因为像.def_readwrite("shape", &b2FixtureDef::shape)这样的东西会给我带来麻烦。我在文档中看到了一些在class_绑定语句中使用智能指针的代码,但这并没有解决问题。

感谢。

1 个答案:

答案 0 :(得分:0)

通过将&shape公开为可设置参数,您尝试为对象(anchorShape)分配地址(shape,因为它就是这样)。语法的&shape部分可能会让您认为您可以修改shape成员的地址,但这是不可能的。因为在地址&shape,您应该编写shape类型的整个对象,但是lua中的anchorFixDef.shape = anchorShape语句只执行指针赋值。这就是luabind窒息的原因。

你必须选择:

  1. 为形状字段提供一个像Lua一样的setter:

    luabind::class_<b2FixtureDef>("b2FixtureDef") .property("shape", &b2FixtureDef::GetShape, b2FixtureDef::SetShape) .def_readwrite("friction", &b2FixtureDef::friction)
    //assuming friction is a basic type and so on

  2. 在{b2Fixture>中设置shape指针。

  3. 前者更为可取,因为它避免了与指针内存管理相关的所有复杂问题,并且很好地结束了类的成员。

    def_readwrite适用于其他成员的原因可能是因为它们具有简单的基本类型(我假设像float或int),它们在Lua中具有等效类型。