lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


First, we need the typemap to use lightuserdata
instead of class
pointer.  There's also a macro, generating fake
walk-throw function,
which later will be wraped by SWIG.

Save the following as "class_p.i".
----------------------------------------------------------------------
-                             class_p.i               
              -
----------------------------------------------------------------------
/* typemap */
%typemap(in, checkfn="lua_islightuserdata") CLASS_P
%{
    $1 = ($type)lua_touserdata(L, $input);
%}

/* helper macro */
/* add inline function:
   SomeClass *SomeClass_p_ctor(SomeClass *pclass)
{return pclass;} */
%define ADD_CLASS_P_CTOR(class_name)
%apply CLASS_P {class_name *};
%inline %{
    class_name *class_name##_p_ctor(class_name
*pclass) {
        return pclass;
    }
%}
%clear class_name *;
%enddef
----------------------------------------------------------------------



Usage:
------------
- In "some_class.i" file 

%module some_module
...
%include "class_p.i"          // <-- Step1

ADD_CLASS_P_CTOR (SomeClass); // <-- Step2
/* further common class declaration */
class SomeClass {
public:
...
};
------------
- In ".cpp" file:
...
SomeClass *psome = new SomeClass;

lua_getglobal(L, "some_module"); // push modulename
lua_pushstring(L, "SomeClass_p_ctor"); 
lua_gettable(L, -2);
lua_remove(L, -2);              //remove table
lua_pushlightuserdata(L, (void *) psome);
lua_call(L,1,1); // Ta-Da! swig-wrapped class pointer
on the stack
------------

Remark:
------------
- Lua doesn't own our class and we should destroy it
by ourselves.
- SWIG generates the following wrapper:

static int _wrap_SomeClass_p_ctor(lua_State* L) {
  int SWIG_arg = -1;
  SomeClass *arg1 = (SomeClass *) 0 ;
  SomeClass *result = 0 ;
  
  if(!lua_islightuserdata(L,1)) SWIG_fail_arg(1);
  
  arg1 = (SomeClass *)lua_touserdata(L, 1);
  
  result = (SomeClass *)SomeClass_p_ctor(arg1);
  SWIG_arg=0;
  SWIG_NewPointerObj(L,result,SWIGTYPE_p_SomeClass,0);
SWIG_arg++; 
  return SWIG_arg;
  
fail:
  lua_error(L);
  return SWIG_arg;
}


Regards, 
Andrew



 
____________________________________________________________________________________
TV dinner still cooling? 
Check out "Tonight's Picks" on Yahoo! TV.
http://tv.yahoo.com/