如何使用SWIG从C++类继承到lua

例如,有一个用C++写的类:

//Say.h
#pragma once

#include <iostream>

class Say
{
public:
    Say() {}
    virtual ~Say() {}
    virtual void SaySomething() { std::cout << "It should not be show..\n"; };
};

inline void CallCppFun(Say& intf) {
    intf.SaySomething();
}

然后编写 Say.i 文件:

//Say.i
%module Test

%{
#include "Say.h"
%}

%include "Say.h"

%inline %{
inline void CallCppFun(Say& intf);
%}

和 main.cpp 文件:

//main.cpp
#include <iostream>

extern "C"
{
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
}

/* 被SWIG封装的库 */
extern "C" int luaopen_Test(lua_State*L);

using namespace std;

int main()
{
    lua_State *L;
    L = luaL_newstate();
    luaL_openlibs(L);
    printf("[C] now loading the SWIG wrapped library\n");
    luaopen_Test(L);
    if (luaL_loadfile(L, "Test.lua") || lua_pcall(L, 0, 0, 0)) {
        printf("[C] ERROR: cannot run lua file: %s", lua_tostring(L, -1));
        exit(3);
    }

    return 0;
}

然后运行以下命令:

swig -c++ -lua say.i

我编译了自动生成的example_wrap.cxx文件和其他cpp文件,并且成功地链接了它们。

我想要在Test.lua中从C++的 Say 类中继承到lua中:

-- Test.lua
Test.Say.SaySomething = function(self)
    print("Inherit from C++ in Lua")
end

my = Test.Say()

my:SaySomething() -- 似乎无法成功继承lua调用中

Test.CallCppFun(my) -- 似乎无法成功在c++调用中继承

打印的结果似乎无法成功继承,无论是在lua调用中还是在c++调用中:

[C] now loading the SWIG wrapped library
It should not be show..
It should not be show..

我知道在Java中支持从C++中继承:generating-java-interface-with-swig

我知道这里有一个类似的问题,但是没有给出我所面临的具体问题的答案:implementing-and-inheriting-from-c-classes-in-lua-using-swig

Lua是否支持使用SWIG从C++类继承到lua,甚至只是使用纯lua?请展示一些代码示例。 如果SWIG不能完成这项任务,是否有第三方库支持它可以轻松完成?

点赞