Bin To Cee

lua-users home
wiki

bin2c 是一个实用工具,可以将二进制文件转换为 C 字符字符串,然后可以通过 #include 嵌入到 C 程序中。

描述

bin2c 例如可用于将 Lua 字节码嵌入到 C 二进制文件中,但它也有更通用的用途(例如嵌入图像文件)。

源代码

Lua 发行版不再包含 bin2c.c,但您可以在早期版本(例如 Lua 5.0 [1])以及 [LuaBinaries] 中找到它。

bin2c 也可以用 Lua 编写。以下 Lua 版本旨在成为一个完整且改进的替代品。此程序及其 C 输出都需要 Lua 5.1。您可以下载 [bin2c.lua],或直接阅读下面的内容。

Lua reimplementation of bin2c

local description = [=[
Usage: lua bin2c.lua [+]filename [status]

Write a C source file to standard output.  When this C source file is
included in another C source file, it has the effect of loading and
running the specified file at that point in the program.

The file named by 'filename' contains either Lua byte code or Lua source.
Its contents are used to generate the C output.  If + is used, then the
contents of 'filename' are first compiled before being used to generate
the C output.  If given, 'status' names a C variable used to store the
return value of either luaL_loadbuffer() or lua_pcall().  Otherwise,
the return values of these functions will be unavailable.

This program is (overly) careful to generate output identical to the
output generated by bin2c5.1 from LuaBinaries.

https://lua-users.lua.ac.cn/wiki/BinTwoCee

Original author: Mark Edgar
Licensed under the same terms as Lua (MIT license).
]=]

if not arg or not arg[1] then
  io.stderr:write(description)
  return
end

local compile, filename = arg[1]:match"^(+?)(.*)"
local status = arg[2]

local content = compile=="+"
  and string.dump(assert(loadfile(filename)))
  or assert(io.open(filename,"rb")):read"*a"

local function boilerplate(fmt)
  return string.format(fmt,
    status and "("..status.."=" or "",
    filename,
    status and ")" or "",
    status and status.."=" or "",
    filename)
end

local dump do
  local numtab={}; for i=0,255 do numtab[string.char(i)]=("%3d,"):format(i) end
  function dump(str)
    return (str:gsub(".", numtab):gsub(("."):rep(80), "%0\n"))
  end
end

io.write(boilerplate[=[
/* code automatically generated by bin2c -- DO NOT EDIT */
{
/* #include'ing this file in a C program is equivalent to calling
  if (%sluaL_loadfile(L,%q)%s==0) %slua_pcall(L, 0, 0, 0); 
*/
/* %s */
static const unsigned char B1[]={
]=], dump(content), boilerplate[=[

};

 if (%sluaL_loadbuffer(L,(const char*)B1,sizeof(B1),%q)%s==0) %slua_pcall(L, 0, 0, 0);
}
]=])

另请参阅


RecentChanges · preferences
编辑 · 历史
最后编辑于 2023 年 2 月 4 日上午 11:02 GMT (diff)