【问题标题】:autobuild of Lua api from C++ application从 C++ 应用程序自动构建 Lua api
【发布时间】:2012-12-17 19:46:44
【问题描述】:

我有一个 C++ 应用程序,我想为这个应用程序设计和提供 Lua API,有什么工具可以帮助我吗?也许有一种方法可以标记一些方法并将它们暴露给 Lua API 层?对于其他语言,我见过可以在解析代码后生成 API 的工具,Lua 有类似的东西吗?

【问题讨论】:

标签: c++ api lua auto-build


【解决方案1】:

我真的很欣赏 LuaBridge 非常轻量级的方法,它只包含 1 个(一个!)头文件来包含在您的应用程序中

https://github.com/vinniefalco/LuaBridge

https://github.com/vinniefalco/LuaBridgeDemo

/** Declare LUA binding for this class
 *
 * @param global_lua
 */
void c_entity::lua_bind(lua_State* L) {
    getGlobalNamespace(L)
        .beginClass<c_entity>("c_entity")
            .addFunction("getSpeed",&c_entity::get_linear_speed)
            .addFunction("getName",&c_entity::get_name)
            .addFunction("getMaxSpeed",&c_entity::get_max_linear_speed)
            .addFunction("getAcceleration",&c_entity::get_max_linear_acceleration)
            .addFunction("getHull",&c_entity::get_hull)
            .addFunction("getArmor",&c_entity::get_armor)
            .addFunction("getShield",&c_entity::get_shield)
            .addCFunction("getStatus",&c_entity::getStatus)
            .addFunction("logTrace",&c_entity::log_trace)
            .addFunction("logInfo",&c_entity::log_info)
            .addFunction("logDebug",&c_entity::log_debug)
            .addFunction("logError",&c_entity::log_error)
        .endClass();
}

【讨论】:

  • 不错!是否有从 c/c++ 声明生成绑定代码的工具?
  • 不,但是一旦你掌握了它,它们就很容易生成我编辑了我的答案以包含一个示例
  • 是的,很简单。我现在明白了——它是如此简单,你不需要自动代码生成?
  • 好吧,别说这么简单,你可以编写自己的生成工具,如果你愿意的话:DI 只是手工完成,因为我只需要公开一个非常有限的类方法子集
【解决方案2】:

查看SWIG。根据您的需求以及“清除”您的 C/C++ 标头的方式,您可以将整个 .h 文件提供给 SWIG 或选择要导出到 Lua 的函数/类(如this 基本示例):

%module example
%{
#include "example.h"
%}
int gcd(int x, int y);
extern double Foo;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-14
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-01
    相关资源
    最近更新 更多