lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


John Belmonte wrote:
> I started implementing Perl-style pack/unpack functions using Lua strings for
> binary data but ran into a snag.  Using strings is fine if you're just looking
> to write data out to a file.
> However if you want to pass the strings to C to be used directly then there are
> alignment issues.

You could try to stuff padding bytes at the head of the string (number of bytes
detected during libsetup).  But I would simply copy it like that:

struct bar {...};
extern void foo(struct bar *);

static int
call_foo(lua_State *L)
	struct bar tmp;

	foo(arg_check_struct(L, 1, &tmp, sizeof(tmp)));
	return 0;

static void *
arg_check_struct(lua_State *L, int argno, void *buf, size_t len)
	size_t l;
	char *str = luaL_check_lstr(L, argno, &l);

	luaL_arg_check(L, l == len, argno, "invalid structure size");
	memcpy(buf, str, l);
	return buf;

Compared to the creation of the packed strings the time to copy it once more
should be negligible.  Only 'P' will not work that way.  The last resort
would be a userdata...

Ciao, ET.