如何索引转换后的用户数据值?

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

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

以下是我的测试代码:

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: 尝试对 userdata 进行索引值 (local 'p')

value

我期望得到的结果 :

3

我该怎么做才能得到我想要的结果?

点赞