Re: FFI opaque pointer approach

  • From: Alex <initrd.gz@xxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Wed, 2 Sep 2015 16:21:23 -0400

On Wed, Sep 2, 2015 at 8:38 AM, Martin Gee <dmarc-noreply@xxxxxxxxxxxxx>
wrote:

I'd like to verify my approach to what seems to be a very common problem.
Is there a FFI best practice for this?

--[[
// ORIG C Header defs
struct _krb5_context;
typedef struct _krb5_context * krb5_context;
krb5_error krb5_init_context(krb5_context *context);

// C program usage
static krb5_context ctx;
krb5_error_code code = krb5_init_context(&ctx)
]]--

-- My LUA def
ffi.cdef[[

void* malloc(size_t);
void free(void*);

typedef int krb5_int32;
typedef krb5_int32 krb5_error_code;
struct _krb5_context;
typedef struct _krb5_context krb5_context;
krb5_error_code krb5_init_context(krb5_context *context);
]]

krb5 = ffi.load("krb5")

-- THIS DOES NOT WORK - size of C type is unknown or too large
-- local ctx = ffi.new('krb5_context*[1]')
-- local ret = krb5.krb5_init_context(ctx[0])

-- THIS DOES WORK
local ctx = ffi.cast('krb5_context*', ffi.C.malloc(64));
local ret = krb5.krb5_init_context(ctx)
if ret == 0 then
ngx.say("SUCCESS->krb5_init_context ret 0")
else
ngx.say("FAILURE->krb5_init_context ret not 0")
end


You're missing the pointer in your FFI typedef

typedef struct _krb5_context krb5_context;
should be:
typedef struct _krb5_context *krb5_context;

--
Sincerely,
Alex Parrill

Other related posts: