如何包装一个参数为结构体指针的C函数,以便可以从Lua调用它?
我有以下 C 函数。我应该如何包装它以便可以从 Lua 脚本调用它?
typedef struct tagT{
int a ;
int b ;
} type_t;
int lib_a_f_4(type_t *t)
{
return t->a * t->b ;
}
如果函数参数类型是 int 或 char * ,我知道如何包装它。我应该对 C 结构使用 table
类型吗?
编辑:我正在使用 SWIG 进行包装,根据此 doc,它似乎我应该自动拥有这个函数 new_type_t(2,3)
,但事实并非如此。
如果你包装一个C结构,它也是 映射到 Lua 用户数据。通过添加一个 元表到用户数据,这 提供了一个非常自然的界面。为了 例如,
结构点{ int x,y; };
用法如下:
p=example.new_Point()
px=3 py=5打印(px,py) 3 5
为工会提供类似的访问权限 以及 C++ 类的数据成员。 C 结构是使用创建的 函数 new_Point(),但适用于 C++ 类的创建仅使用 命名 Point()。
I have the follwing C function. How should I wrap it so it can be called from a Lua script?
typedef struct tagT{
int a ;
int b ;
} type_t;
int lib_a_f_4(type_t *t)
{
return t->a * t->b ;
}
I know how to wrapr it if the function parameter type were int
or char *
. Should I use table
type for a C structure?
EDIT: I am using SWIG for the wraping , according to this doc, It seems that I should automatically have this function new_type_t(2,3)
, but it is not the case.
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().
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我匆忙把这些放在一起。它编译了;然后我做了一些最后一刻的编辑。我希望它接近正确的事情。翻遍Lua手册,看看所有不熟悉的函数。
I put this together in a hurry. It compiled; then I did a few last-minute edits. I hope it's close to the right thing. Go through the Lua manual and look at all the unfamiliar functions.
解决了。
还应该在
example.i
文件中添加类型定义,仅包含.h
是不够的。使用
example.Point()
,而不是example.new_Point()
(SWIG 版本 1.3.35)Solved.
Should also add the type definition in the
example.i
file , just include the.h
is not enough.use
example.Point()
,notexample.new_Point()
(SWIG Version 1.3.35)