lua - Swig 类型转换为派生类?

标签 lua type-conversion swig casting

我注意到 Swig 提供了一整套函数来允许将对象类型转换为其父类。然而,在 C++ 中可以生成如下所示的函数:

A * getAnObject()
{
  if(someBoolean)
    return (A *) new B;
  else
    return (A *) new C;
}

其中“A”是类“B”和“C”的父类。然后,可以根据需要将返回的指针类型转换为“B”类型或“C”类型,例如:

B * some_var = (B *) getAnObject();

是否有某种方法可以使用包装器在脚本语言中对运行时从通用指针生成函数接收到的对象进行类型转换? (就我而言,Lua?)我有一个函数可以生成大约一百个可能的类之一,并且我想避免编写必须在 C++ 中维护的巨大 switch 结构。当我收到通用指针时,我还有一个我想要将其转换为的数据类型的字符串表示形式。

有什么想法吗?谢谢!

-- 编辑--

我注意到 SWIG 提供为我的所有类生成复制构造函数。如果我让它生成这些,我可以做如下的事情吗?:

var = myModule.getAnObject(); -- Function that returns an object type-cast down to a pointer of the parent class, as in the function getAnObject() above.
var = myModule.ClassThatExtendsBaseClass(var); -- A copy constructor that SWIG theoretically creates for me

然后让 var 成为继承类的实例,知道它是继承类的实例?

最佳答案

我为我的问题找到了解决方案。我对 lua 的垃圾收集很陌生,所以我不确定它是否是防内存泄漏的,但它做了我需要它做的事情。 (这也不是万无一失的——如果你传递一个有效的数据类型和一个不应该被转换为该数据类型的对象,就会产生不好的结果。)

================================================== ===================================

static int lua_typecast_Object_I(lua_State *L)
{
        void * myDataPtr;
        void ** ptrToPtr = &myDataPtr;

        // Attempt to convert the first parameter to a pointer of
        // the lowest parent type from which all other data types 
        // inherit. e.g. "Object_I"

        if (!SWIG_IsOK(SWIG_ConvertPtr(L, 1, ptrToPtr, SWIGTYPE_p_Namespace1__Object_I, 0)))
        {
                lua_pushnumber(L, -1);
                lua_pushstring(L,"Pointer conversion in typecast function failed.");
                return 2;
        }

        const char * type_name = luaL_checkstring(L, 2);

        // Search the SWIG module for a swig_type_info that contains the data
        // type string that was passed as the second parameter

        swig_module_info* module=SWIG_GetModule(L);
        swig_type_info *type = SWIG_TypeQueryModule(module,module,type_name);
        if(type == NULL)
        {
                lua_pushnumber(L, -2);
                lua_pushstring(L,"Failed to find swig_type_info for specified type.");
                return 2;
        }

        // Using the swig_type_info that we found, create a new object on 
        // the stack of the desired data type and return.

        SWIG_Lua_NewPointerObj(L, myDataPtr, type, 0);
        return 1;
}

================================================== ===================================

希望对某人有帮助!

关于lua - Swig 类型转换为派生类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/966894/

相关文章:

database - 如何在 lua-dbi 中使用准备好的语句?

javascript - 将字符串转换为日期时间

c++ - 如何使用 swig Python 重载下标运算符

python - 为 C 库创建 Python 绑定(bind)的 SWIG 问题

c++ - 具有 C++ 基类的 Python 子类

iphone - Iphone 上的 Lua 解释器

lua多重赋值

Lua:在函数中作为一个传递的引用参数

java - 将字符串转换为 hashtable 会出现 NullPointerException

c - 从 char * 到 int 的类型转换