Skip to content

Commit

Permalink
Add ffi example
Browse files Browse the repository at this point in the history
  • Loading branch information
creationix committed Jun 30, 2012
1 parent a018346 commit c7c6fc7
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
31 changes: 31 additions & 0 deletions ffi.lua
@@ -0,0 +1,31 @@
local ffi = require "ffi"
local fs = require "fs"

-- Feed the header to ffi
ffi.cdef(fs.readFileSync("uvffi.h"))
-- Cache the C namespace object
local C = ffi.C
-- Create our lua module
local uv = {}

local function uvCheck(err)
if err.code == 0 then return end
local name = ffi.string(C.uv_err_name(err))
local message = ffi.string(C.uv_strerror(err))
error(name .. ": " .. message)
end

function uv.getProcessTitle()
local buffer = ffi.new("char[MAX_TITLE_LENGTH]")
uvCheck(C.uv_get_process_title(buffer, C.MAX_TITLE_LENGTH))
return ffi.string(buffer)
end

function uv.setProcessTitle(title)
uvCheck(C.uv_set_process_title(title))
end

p(uv.getProcessTitle())
uv.setProcessTitle("FOOMONKEY")
p(uv.getProcessTitle())

8 changes: 8 additions & 0 deletions uvffi.h
@@ -0,0 +1,8 @@
/* uvffi.h */
enum { MAX_TITLE_LENGTH = 8192 }
struct uv_err_s { int code; int sys_errno_; };
typedef struct uv_err_s uv_err_t;
uv_err_t uv_get_process_title(char* buffer, size_t size);
uv_err_t uv_set_process_title(const char* title);
const char* uv_strerror(uv_err_t err);
const char* uv_err_name(uv_err_t err);

0 comments on commit c7c6fc7

Please sign in to comment.