【发布时间】:2016-09-27 09:55:16
【问题描述】:
例如,有一个用 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>
}
/* the SWIG wrappered library */
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中做的是从lua中的C++Say类继承:
-- Test.lua
Test.Say.SaySomething = function(self)
print("Inherit from C++ in Lua")
end
my = Test.Say()
my:SaySomething() -- doesn't appear to inherit successfully in lua call
Test.CallCppFun(my) -- doesn't appear to inherit successfully in c++ call
在 lua 调用和 c++ 调用中,print 的结果似乎都没有成功继承:
[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 从 lua 中的 C++ 类继承,甚至只使用纯 lua?请显示一些代码示例。 如果 SWIG 无法完成这项工作,是否有一些第三方库支持可以轻松完成?
【问题讨论】:
标签: c++ inheritance lua swig