SWIG_NewPointerObj和values始终为空。

我正在使用SWIG将C++对象包装起来用于lua,我试图传递数据到我的lua脚本中的方法,但它总是输出为'nil'

这是我的C++代码:

void CTestAI::UnitCreated(IUnit* unit){
    lua_getglobal(L, "ai");
    lua_getfield(L, -1, "UnitCreated");
    swig_module_info *module = SWIG_GetModule( L );
    swig_type_info *type = SWIG_TypeQueryModule( module, module, "IUnit *" );
    SWIG_NewPointerObj(L,unit,type,0);
    lua_epcall(L, 1, 0);
}

这是我的lua代码:

function AI:UnitCreated(unit)
   if(unit == nil) then
      game:SendToConsole("I CAN HAS nil ?")
   else
      game:SendToConsole("I CAN HAS UNITS!!!?")
   end
end

unit总是为nil。我已经检查了C++代码,unit指针从未无效/空

我也尝试过:

void CTestAI::UnitCreated(IUnit* unit){
    lua_getglobal(L, "ai");
    lua_getfield(L, -1, "UnitCreated");
    SWIG_NewPointerObj(L,unit,SWIGTYPE_p_IUnit,0);
    lua_epcall(L, 1, 0);
}

它的结果也是相同的。

为什么会失败?我该如何修复它?

原文链接 https://stackoverflow.com/questions/2406410

点赞
stackoverflow用户189205
stackoverflow用户189205

当你在使用 function AI:UnitCreated(unit) 中的冒号时,它会创建一个隐藏的 self 参数,接收 AI 实例。实际上,它的行为就像这样:

function AI.UnitCreated(self, unit)

因此在从 C 中调用该函数时,你需要传递两个参数:ai 实例和 unit 参数。由于只传递了一个参数,self 被设置为它,而 unit 被设置为 nil

2010-03-09 20:21:15