我正在研究如何将完整的脚本支持集成到我的应用程序中,但在计划我的C API成为LUA友好程序时遇到了一些问题。如何为LUA创建安全的C接口
基本上我得到了通过init和免费 功能创建这样结构的一串:
[test.h]
typedef struct
{
char name[ 50 ];
} Test;
Test *TestAdd(char *name);
Test *TestDelete(Test *test);
[test.c的]
Test *TestAdd(char *name)
{
Test *test = (Test *) calloc(1, sizeof(Test));
strcpy(test->name, name);
return test;
}
Test *TestDelete(Test *test)
{
free(test);
return NULL;
}
我使用swig生成LUA模块,因此我创建了以下接口文件:
[test.i]
%module test
%{
%}
Test *TestAdd(char *name);
Test *TestDelete(Test * test);
一切都正常工作,如果用户代码是这样的:
a = test.TestAdd("test")
a = test.TestDelete(a)
if(a != nil) print(a.name)
但是,如果用户代码是这样的:
a = test.TestAdd("test")
test.TestDelete(a)
if(a != nil) print(a.name) -- Crash the app with bad_access (not just a LuaVM error).
甚至最差:
a = test.TestAdd("test")
test.TestDelete(a)
test.TestDelete(a)
-- Another way of making crash my app completely!
有没有我可以在C中创建一组API来避免这种问题,并且可以让用户以安全的方式安全地添加/删除和访问属性,从而不会产生“不良访问”错误并使整个程序崩溃,最好的办法就是LUAVM只是返回一个错误并继续执行。
我一直在寻找和尝试不同的方法,我的C API来避免这个问题,但失败了......
任何人都可以帮助我或者给我一些指点关于要去的方向与此有关。
由于提前,
如果您可以将指针设置为NULL,那么将它释放两次不会成为问题,您只需在每个使用它的函数中检查它是否为NULL即可。 – 2011-12-16 02:48:37