我正在尝试使用SWIG封装一个带有变量参数的C函数,如下所示。
void post(const char *fmt, ...)
{
char buf[MAXPDSTRING];
va_list ap;
t_int arg[8];
int i;
va_start(ap, fmt);
vsnprintf(buf, MAXPDSTRING-1, fmt, ap);
va_end(ap);
strcat(buf, "\n");
dopost(buf);
}
但是当我在Lua中运行函数时,它只在我使用1个参数时才起作用。我不能用下面的风格写。
pd.post("NUM : %d", 123);
我得到了下面的错误。
Error in post expected 1..1 args, got 2
有没有可能用SWIG包装一个带有可变参数的C函数?
如果有任何帮助,我将不胜感激。谢谢!
发布于 2018-06-04 11:54:33
免责声明:不是一个真正的答案,因为我没有找到覆盖SWIG的参数检查的方法,所以我可以自己处理varargs。这可以通过将我下面展示的方法与this answer相结合来解决。
链接和进一步的阅读
SWIG documentation
中的
纯C包装器
我准备了一个示例,如何使用libffi (documentation)将对可变Lua函数的调用转换为可变C函数。
目前,该代码只处理int
(需要Lua5.3)、double
和const char *
参数。它也可以简单地扩展到更多的类型。请记住,这种方法是极其不安全的。使用不受支持的格式将导致分段错误(格式字符串未选中)。例如,在Lua5.2上编译并尝试使用整数格式,如下所示
printf("Hello World! %d %d %d\n", 1, 5, 7)
将导致
Hello World! 0 0 0
如果你很幸运,它不会在你身上出现段错误,但是在valgrind这样的内存调试器中运行程序会发现你正在做一些令人讨厌的事情。
// clang -Wall -Wextra -Wpedantic -std=c99 -g -I/usr/include/lua5.3 test.c -llua5.3 -lffi
#include <stdio.h>
#include <stdlib.h>
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
#include <ffi.h>
static int l_printf(lua_State *L) {
typedef union {
int integer;
double number;
const char *string;
} variant;
int argc = lua_gettop(L);
variant *argv = malloc(argc * sizeof(variant));
ffi_cif cif;
ffi_type **types = malloc(argc * sizeof(ffi_type *));
void **values = malloc(argc * sizeof(void *));
for (int i = 0; i < argc; ++i) {
int j = i + 1;
switch (lua_type(L, j)) {
case LUA_TNUMBER:
#if LUA_VERSION_NUM >= 503
if (lua_isinteger(L, j)) {
types[i] = &ffi_type_sint;
argv[i].integer = lua_tointeger(L, j);
values[i] = &argv[i].integer;
} else
#endif
{
types[i] = &ffi_type_double;
argv[i].number = lua_tonumber(L, j);
values[i] = &argv[i].number;
}
break;
case LUA_TSTRING:
types[i] = &ffi_type_pointer;
argv[i].string = lua_tostring(L, j);
values[i] = &argv[i].string;
break;
default:
puts("Unhandled argment type");
abort();
break;
}
}
// If preparing the FFI call fails we simply push -1 to indicate
// that printf failed
int result = -1;
if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, argc, &ffi_type_sint, types) ==
FFI_OK) {
ffi_call(&cif, (void (*)())printf, &result, values);
}
free(values);
free(types);
free(argv);
lua_pushinteger(L, result);
return 1;
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <script.lua>\n", argv[0]);
return 1;
}
lua_State *L = luaL_newstate();
luaL_openlibs(L);
lua_pushcfunction(L, l_printf);
lua_setglobal(L, "printf");
if (luaL_dofile(L, argv[1]) != 0) {
fprintf(stderr, "lua: %s\n", lua_tostring(L, -1));
lua_close(L);
return 1;
}
lua_close(L);
}
对Lua 5.3进行编译,我们可以运行以下示例:
print(printf("Hello World! %d %d %d\n", 1, 5, 7) .. " bytes written")
print(printf("Hello %d %f World! %s\n", 1, 3.14, "ABC") .. " bytes written")
输出:
Hello World! 1 5 7
19 bytes written
Hello 1 3.140000 World! ABC
28 bytes written
一口大口的尝试
我提出了一个可以在SWIG中使用的变体,但假设所有参数都可以转换为string
。在这里,我只是简单地将printf
声明为一个接受string
类型的10个参数的函数(如果需要更多参数,只需增加数量)。
%varargs(10, const char * = NULL) printf;
int printf(const char *fmt, ...);
这将调用具有10个字符串的printf
函数,这些字符串缺省为空(NULL
)。因此,我编写了一个action
,它将每个参数转换为相应的类型(int
、double
、string
)。因为SWIG参数检查器已经对每个参数调用了lua_tostring
,所以对lua_type
的调用总是会导致LUA_TSTRING
,而不管实际的参数类型是什么。这就是我使用lua_tointegerx
和lua_tonumberx
从字符串转换回原始类型的原因。再加上基于后续转换的效率极低的缺陷,这给了我们一个类似于上面给出的普通C包装器的包装器。
%module printf
%{
#include <ffi.h>
%}
%feature("action") printf {
typedef union {
int integer;
double number;
const char *string;
} variant;
int argc = lua_gettop(L);
variant *argv = malloc(argc * sizeof(variant));
ffi_cif cif;
ffi_type **types = malloc(argc * sizeof(ffi_type *));
void **values = malloc(argc * sizeof(void *));
for (int i = 0; i < argc; ++i) {
int j = i + 1;
int flag = 0;
types[i] = &ffi_type_sint;
argv[i].integer = lua_tointegerx(L, j, &flag);
values[i] = &argv[i].integer;
if (flag) { continue; }
types[i] = &ffi_type_double;
argv[i].number = lua_tonumberx(L, j, &flag);
values[i] = &argv[i].number;
if (flag) { continue; }
types[i] = &ffi_type_pointer;
argv[i].string = lua_tostring(L, j);
values[i] = &argv[i].string;
if (argv[i].string) { continue; }
puts("Unhandled argment type");
abort();
break;
}
// If preparing the FFI call fails we simply push -1 to indicate
// that printf failed
result = -1;
if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, argc, &ffi_type_sint, types) ==
FFI_OK) {
ffi_call(&cif, (void (*)())printf, &result, values);
}
free(values);
free(types);
free(argv);
};
%varargs(10, const char * = NULL) printf;
int printf(const char *fmt, ...);
swig -lua test.i
clang -Wall -Wextra -Wpedantic -std=c99 -I/usr/include/lua5.3 -fPIC -shared test_wrap.c -o printf.so -llua5.3 -lffi
local printf = require"printf"
printf.printf("Hello %d %f %s World!\n", 1, 3.14, "ABC")
Hello 1 3.140000 ABC World!
结束语
最后,在Lua中,这是一种非常低效的格式化字符串的方式。我不知道在C中除了printf
系列函数之外还有其他的变量函数,也就是说,它们都执行字符串格式化。在Lua中,使用string.format
和如下的函数调用可以更有效地完成这项工作
do_something("Hello %d %f %s World!\n", 1, 3.14, "ABC")
应该简单地避免,而支持稍微更冗长但更健壮的
do_something(string.format("Hello %d %f %s World!\n", 1, 3.14, "ABC"))
https://stackoverflow.com/questions/50563785
复制相似问题