【发布时间】:2020-05-19 20:01:03
【问题描述】:
编辑:由于回复似乎集中在 void* 到 typed* 的转换,我已将示例更改为更具体的内容。
我有一堆函数都遵循相同的模式:
int prefix_name(void *p) {
my_type *t = (my_type *)p;
<possibly other common lines>
<function-specific code>
}
static int mod_name(lua_State *L) {
lua_pushlightuserdata(L, (void *)&KEY);
lua_gettable(L, LUA_REGISTRYINDEX);
typed *t = lua_touserdata(L, -1);
<function-specific code>
}
为了减少打字和拼写错误,我创建了一个简单的宏:
#define API_FUNCTION(name) static int mod_ ## name(lua_State *L) {\
lua_pushlightuserdata(L, (void *)&KEY);\
lua_gettable(L, LUA_REGISTRYINDEX);\
typed *t = lua_touserdata(L, -1);
所以我可以把每个函数写成
API_FUNCTION(name)
<function-specific code>
}
这很好用,但是因为左大括号在宏中,这会破坏我的编辑器中的大括号匹配功能。有什么我可以在宏中改变的东西,所以我可以写
API_FUNCTION(name) {
<function-specific code>
}
并让事情按预期工作?
一种可能的替代方法是将宏定义为
API_FUNCTION(name, ...) int prefix_ ## name(void *p) {\
my_type *t = (my_type*)p;\
<possibly other common lines>
__VA_ARGS__
}
然后将其称为
API_FUNCTION(name,
<function-specific code>
)
乍一看确实可行,但我不喜欢它的外观,而且它还使预处理器输出更大。
编辑 2:基于 Orel 的代码,我想这样的东西会起作用,虽然它相当丑陋并且意味着额外的函数调用:
#define API_FUNCTION(name) static int mod_ ## name ## _internal(lua_State *L, typed *t);\
static int mod_ ## name(lua_State *L) {\
lua_pushlightuserdata(L, (void *)&KEY);\
lua_gettable(L, LUA_REGISTRYINDEX);\
typed *t = lua_touserdata(L, -1);\
return mod_ ## name ## _internal(L,t); \
} \
static int mod_ ## name ## _internal(lua_State *L, typed *t)
【问题讨论】:
-
为此使用函数怎么样?除非您发布实际代码,否则我个人无法真正帮助您解决宏问题。
-
可能有点难看,但您可以定义一个结束函数宏:
#define API_FUNCEND }并使用它来代替显式右大括号 - 这应该让您的编辑器满意。 (您甚至可以在该宏中包含任何常见的return代码?) -
编写一个以
my_type *为参数的函数并创建调用它的宏。我真的不明白你用这种宏赢得了什么。