c - 如何包装一个参数是指向结构的指针的C函数,以便它可以从Lua调用?

标签 c lua swig

我有以下 C 函数。我应该如何包装它以便可以从 Lua 脚本中调用它?

typedef struct tagT{
    int a ; 
    int b ;
} type_t;

int lib_a_f_4(type_t *t)
{
     return t->a * t->b ;
}

如果函数参数类型是 intchar *,我知道如何包装它。我应该为 C 结构使用 table 类型吗?

编辑:根据这个 doc,我正在使用 SWIG 进行包装,好像我应该自动有这个函数 new_type_t(2,3) ,但事实并非如此。

If you wrap a C structure, it is also mapped to a Lua userdata. By adding a metatable to the userdata, this provides a very natural interface. For example,

struct Point{ int x,y; };

is used as follows:

p=example.new_Point() p.x=3 p.y=5 print(p.x,p.y) 3 5

Similar access is provided for unions and the data members of C++ classes. C structures are created using a function new_Point(), but for C++ classes are created using just the name Point().

最佳答案

我匆忙把它放在一起。它编译;然后我做了一些最后一刻的编辑。我希望它接近正确的事情。翻阅 Lua 手册,查看所有不熟悉的功能。

#include <lua.h>
#include <lauxlib.h>

const char *metaname = "mine.type_t"; // associated with userdata of type type_t*

typedef struct tagT{
    int a ; 
    int b ;
}type_t;


int lib_a_f_4(type_t *t)
{
     return t->a * t->b ;
}

static int lua_lib_a_f_4(lua_State *L) {
  type_t *t = luaL_checkudata(L, 1, metaname);  // check argument type
  lua_pushnumber(L, (lua_Number)lib_a_f_4(t));
  return 1;
}

static int lua_new_t(lua_State *L) { // get Lua to allocate an initialize a type_t*
  int a = luaL_checkint(L, 1);
  int b = luaL_checkint(L, 2);
  type_t *t = lua_newuserdata(L, sizeof(*t));
  luaL_getmetatable(L, metaname);
  lua_setmetatable(L, -2);
  t->a = a;
  t->b = b;
  return 1;
}

static const struct luaL_reg functions[] = {
  { "lib_a_f_4", lua_lib_a_f_4 },
  { "new_t", lua_new_t },
  { NULL, NULL }
};

int mylib_open(lua_State *L) {
  luaL_register(L, "mylib", functions);
  luaL_newmetatable(L, metaname);
  lua_pop(L, 1);
  return 1;
}

//compile and use it in lua
root@pierr-desktop:/opt/task/dt/lua/try1# gcc -shared -o mylib.so -I/usr/include/lua5.1/ -llua *.c -ldl
root@pierr-desktop:/opt/task/dt/lua/try1# lua
Lua 5.1.3  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> require("mylib")
> t=mylib.new_t(2,3)
> mylib.lib_a_f_4(t)
> print(mylib.lib_a_f_4(t))
6
> 

关于c - 如何包装一个参数是指向结构的指针的C函数,以便它可以从Lua调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2521244/

相关文章:

c - 如何从 GHashTable 访问 gpointer 指向的 GString

lua - Awesome 3.5 - 顶部有两个面板(wiboxes)

python - 导入 swig 生成的模块时,Python 提示缺少删除方法

types - 表中的 Lua 表显示为 Nil

java - 如何避免在 Java 和 native C++ 代码之间复制数据

python - 使用 SWIG 打印为 Python 包装的 C++ 类时不调用 __str__()

c - 为什么这个二分查找程序会出错?

c - 使用 poll 在 C 中进行套接字连接超时

c - memcpy 和二维数组

c++ - LuaPlus:如何让函数返回一个表?