在Lua绑定C代码中正确处理malloc调用
我正在写一个小型的装订库。目前,我提供了一个非常简单的结构来保存键/值,其中我的在Lua绑定C代码中正确处理malloc调用,c,lua,malloc,C,Lua,Malloc,我正在写一个小型的装订库。目前,我提供了一个非常简单的结构来保存键/值,其中我的值是一个无效指针 struct kvPair { enum EVENT_TYPE type; char *key; void *value; }; typedef struct kvPair KeyValuePair; KeyValuePair kvPairWithNumber(char *key, float number) { KeyValuePair
值
是一个无效指针
struct kvPair {
enum EVENT_TYPE type;
char *key;
void *value;
};
typedef struct kvPair KeyValuePair;
KeyValuePair kvPairWithNumber(char *key, float number)
{
KeyValuePair kv;
float *aux = malloc(sizeof(float)); // <-- help
*aux = number;
kv.key = key;
kv.type = NUMBER;
kv.value = aux;
return kv;
}
也许我可以预先分配一块内存,也许可以用我自己更简单的实现覆盖malloc调用(使用简单堆栈的自定义内存分配器?)
希望收到反馈和示例,简单为佳 你肯定不想退出。任何脚本或扩展都不应使整个解释器崩溃 基本上有两种方法来表示错误。第一种方法是使用or,这是由C API提供的。第二种方法更像是一种策略:(通常与
assert
)结合使用)
您正在用C编写扩展,因此基本上只能通过返回代码进行C风格的错误处理。您很可能需要更改函数签名以支持此功能
int kvPairWithNumber(KeyValuePair * kv, char *key, float number)
{
float *aux = malloc(sizeof(float));
if (aux == NULL) {
return 0;
// note: you could instead just put lua_error here
}
*aux = number;
kv->key = key;
kv->type = NUMBER;
kv->value = aux;
return 1;
}
然后,您可以处理Lua函数中的错误:
int my_lua_function(lua_State * L)
{
KeyValuePair kv = {0};
// first method:
if (!kvPairWithNumber(&kv, "asdf", 1.0)) {
luaL_error(L, "could not create pair!");
}
// second method:
if (!kvPairWithNumber(&kv, "asdf", 1.0)) {
lua_pushnil(L);
lua_pushstring(L, "could not create a pair!");
return 2;
}
}
使用扩展名的Lua代码如下所示:
-- first method:
local result = xpcall(my_lua_function, error_handler)
-- note: if you need to pass args, you will need a closure
local result = xpcall(function() my_lua_function(x, y, z) end, error_handler)
-- second method:
local result = assert(my_lua_function())
你肯定不想退出。任何脚本或扩展都不应使整个解释器崩溃 基本上有两种方法来表示错误。第一种方法是使用or,这是由C API提供的。第二种方法更像是一种策略:(通常与
assert
)结合使用)
您正在用C编写扩展,因此基本上只能通过返回代码进行C风格的错误处理。您很可能需要更改函数签名以支持此功能
int kvPairWithNumber(KeyValuePair * kv, char *key, float number)
{
float *aux = malloc(sizeof(float));
if (aux == NULL) {
return 0;
// note: you could instead just put lua_error here
}
*aux = number;
kv->key = key;
kv->type = NUMBER;
kv->value = aux;
return 1;
}
然后,您可以处理Lua函数中的错误:
int my_lua_function(lua_State * L)
{
KeyValuePair kv = {0};
// first method:
if (!kvPairWithNumber(&kv, "asdf", 1.0)) {
luaL_error(L, "could not create pair!");
}
// second method:
if (!kvPairWithNumber(&kv, "asdf", 1.0)) {
lua_pushnil(L);
lua_pushstring(L, "could not create a pair!");
return 2;
}
}
使用扩展名的Lua代码如下所示:
-- first method:
local result = xpcall(my_lua_function, error_handler)
-- note: if you need to pass args, you will need a closure
local result = xpcall(function() my_lua_function(x, y, z) end, error_handler)
-- second method:
local result = assert(my_lua_function())
为什么不将值存储在结构中(可能在联合中)而不是存储指针呢?这可能会更好。。。你能写一个代码示例吗?:)我最终使用了一个C联合。为什么不将值存储在结构中(可能是联合中)而不是存储指针呢?那可能更好。。。你能写一个代码示例吗?:)我最终使用了C联合体。