首页 > 解决方案 > 如何索引转换后的用户数据值?

问题描述

我尝试使用将 C++ 类转换为 void 指针lua_touserdata(),然后使用lua_pushlightuserdata().

但是,一旦进行转换,我就无法在类中索引变量。

这是我的测试代码:

MyBindings.h

class Vec2
{
public:
    Vec2():x(0), y(0){};
    Vec2(float x, float y):x(x), y(y){};
    float x, y;
};

void *getPtr(void *p)
{
    return p;
}

MyBindings.i

%module my
%{
    #include "MyBindings.h"
%}

%typemap(typecheck) void* 
{
    $1 = lua_isuserdata(L, $input);
}
%typemap(in) void* 
{
    $1 = lua_touserdata(L, $input);
}

%typemap(out) void* 
{
    lua_pushlightuserdata(L, $1);
    ++SWIG_arg;
}

%include "MyBindings.h"

main.cpp

#include "lua.hpp"

extern "C"
{
    int luaopen_my(lua_State *L);
}

int main()
{
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);
    luaopen_my(L);
    lua_settop(L, 0);
    const int ret = luaL_dostring(L, "local vec = my.Vec2(3, 4)\n"
                                     "local p = my.getPtr(vec)\n"
                                     "print(p.x)");
    if (ret)
    {
        std::cout << lua_tostring(L, -1) << '\n';
    }
    lua_close(L);
}

我得到的结果:

[string "local vec = my.Vec2(3, 4)..."]:3: 尝试索引用户数据值 (local 'p')

我期望的结果:

3

我应该怎么做才能得到我期望的结果?

标签: c++luaswiglua-userdatatypemaps

解决方案


如果你想这样做,你必须调整你的设计。首先,该功能getPtr无法工作,因为它太通用了。SWIG 不可能神奇地猜测类型并做正确的事情。您至少必须修复输入的类型。

MyBindings.h

struct Vec2 {
    Vec2() : x(0), y(0){};
    Vec2(float x, float y) : x(x), y(y){};
    float x, y;
};

void *getPtr(Vec2 &p) { return &p; }

再说一次,你真的确定要这样做吗?因为会变丑!

您至少需要两个元方法__index__newindex来通过指针获取和设置向量的元素。我在接口文件的文字块 ( %{ ... %}) 中实现了这些,但您也可以将它们移动到标题并将此标题包含在文字块中。

现在你必须让 Lua 知道你定义的元方法并将它们插入到一个命名的元表中,这样你就可以将类型指针Vec2与其他指针区分开来。%init因此,当解释器启动时,您必须在接口文件的部分中注册元表。

因为您必须去掉 的void*输入参数getPtr,所以可以删除typecheck和类型映射。必须调整类型in图。out我们必须为适合指针的用户数据分配内存Vec2。我们将 userdata 设置为这个指针并将Vec2元表贴在它上面。现在这非常容易,不是吗?(讽刺)

MyBindings.i

%module my
%{
    #define SWIG_FILE_WITH_INIT
    #include <string>
    #include "MyBindings.h"

    static int setVec2(lua_State *L) {
        Vec2 *v = *static_cast<Vec2 **>(luaL_checkudata(L, 1, "Vec2"));
        luaL_argcheck(L, v != nullptr, 1, "invalid pointer");
        std::string index = luaL_checkstring(L, 2);
        luaL_argcheck(L, index == "x" || index == "y", 2, "index out of range");
        luaL_argcheck(L, lua_isnumber(L, 3), 3, "not a number");
        float record = lua_tonumber(L, 3);

        if (index == "x") {
            v->x = record;
        } else if (index == "y") {
            v->y = record;
        } else {
            assert(false); // Can't happen!
        }

        return 0;
    }

    static int getVec2(lua_State *L) {
        Vec2 *v = *static_cast<Vec2 **>(luaL_checkudata(L, 1, "Vec2"));
        luaL_argcheck(L, v != nullptr, 1, "invalid pointer");
        std::string index = luaL_checkstring(L, 2);
        luaL_argcheck(L, index == "x" || index == "y", 2, "index out of range");

        if (index == "x") {
            lua_pushnumber(L, v->x);
        } else if (index == "y") {
            lua_pushnumber(L, v->y);
        } else {
            assert(false); // Can't happen!
        }

        return 1;
    }

    static const struct luaL_Reg Vec2_meta[] = {
        {"__newindex", setVec2},
        {"__index", getVec2},
        {nullptr, nullptr} // sentinel
    };
%}

%init %{
    luaL_newmetatable(L, "Vec2");
    luaL_setfuncs(L, Vec2_meta, 0);
    lua_pop(L, 1);
%}

%typemap(out) void* 
{
    void * udata = lua_newuserdata(L, sizeof(Vec2 *));
    *static_cast<void **>(udata) = $1;
    luaL_getmetatable(L, "Vec2");
    lua_setmetatable(L, -2);
    ++SWIG_arg;
}

%include "MyBindings.h"

让我们看看它是否有效。

test.lua

local my = require("my")
local vec = my.Vec2(3, 4)
local p = my.getPtr(vec)
print(p.x, p.y)
p.x = 1.0
p.y = 2.0
print(p.x, p.y)
print(vec.x, vec.y)
$ swig -lua -c++ MyBindings.i
$ clang++ -Wall -Wextra -Wpedantic -I/usr/include/lua5.3 -fPIC -shared MyBindings_wrap.cxx -o my.so -llua5.3
$ lua5.3 test.lua
3.0 4.0
1.0 2.0
1.0 2.0

如果您使用轻量级用户数据可能会更容易一些,但缺点是所有轻量级用户数据将共享相同的元表,因此您只能对一种对象执行此操作。


回复评论

将指向特定类型的指针转​​换void*为类型擦除称为类型擦除,因为您会丢失有关所包含数据的所有信息。因此,您在恢复类型时必须小心,您实际上恢复了正确的类型。强制转换为不相关的类型是未定义的行为,如果幸运的话,会导致程序崩溃。

您可能不希望能够void*Vec2. 铸造到那时的目的是什么void*,当您无论如何都想保留原始含义时。相反,您希望拥有两个功能,getPtr并且getVec2. 该getPtr函数擦除类型并为您提供一个void*在 Lua 中不可用的对象,但可以方便地传递给接受任意数据的回调函数作为void*. 完成后,该getVec2函数将类型恢复为Vec2

在示例中,getVec2函数通过引用返回,即返回的对象将是对您调用的对象的引用getPtr。这也意味着,如果原始对象被垃圾回收,则您的指针无效,这将使您的应用程序崩溃。

MyBindings.h

struct Vec2 {
    Vec2() : x(0), y(0){};
    Vec2(float x, float y) : x(x), y(y){};
    float x, y;
};

void *getPtr(Vec2 &p) { return &p; }
Vec2 &getVec2(void *p) { return *static_cast<Vec2 *>(p); }

MyBindings.i

%module my
%{
    #define SWIG_FILE_WITH_INIT
    #include "MyBindings.h"
%}

%include "MyBindings.h"

test.lua

local my = require("my")
local vec = my.Vec2(3, 4)
-- Erase the type of vec to pass it around
local p = my.getPtr(vec)
-- Then restore the type using getVec2
local v = my.getVec2(p)
-- Take care! v is a reference to vec
v.x = 1.0
v.y = 2.0
print(v.x, v.y)
print(vec.x, vec.y)

示例调用:

$ swig -lua -c++ MyBindings.i
$ clang++ -Wall -Wextra -Wpedantic -I/usr/include/lua5.3 -fPIC -shared MyBindings_wrap.cxx -o my.so -llua5.3
$ lua5.3 test.lua 
1.0 2.0
1.0 2.0

要查看引用语义失败,请放置vec = nil collectgarbage()local p = my.getPtr(vec). 它不会在我的机器上崩溃,但 Valgrind 报告无效的读取和写入。


推荐阅读