RE: ffi initializer bit me today

  • From: William Adams <william_a_adams@xxxxxxx>
  • To: "luajit@xxxxxxxxxxxxx" <luajit@xxxxxxxxxxxxx>
  • Date: Sat, 8 Sep 2012 20:38:06 +0000

Yah, I've come across some 'non-intuitive' behaviors over the past few months 
of coding with FFI.   One of the ones I find interesting is the treatment of 
pointers within a struct: ffi.cdef[[typedef struct point {int x;int y;} point; 
typedef struct Rect {  point origin;  int width;  int height;} Rect; void 
cfunc(point * apoint)]] -- pass pointer to 'origin' to a c function:arect = 
ffi.new("Rect");ffi.C.cfunc(arect.origin); This will actually work, which was 
not immediately obvious to me. I think in your first case, I'd rather FFI 
didn't do any real magic, particularly where it will result in overwriting a 
buffer, whose size it already knows. "strings" are a funky thing in Lua.  
Sometimes they're asciiz null terminated 'strings', and sometimes they're just 
immutable buffers of random data, including 'null' characters.  I think the FFI 
should be neutral in these cases, and not treat them as asciiz strings. -- 
William

===============================
- Shaping clay is easier than digging it out of the ground.

 > From: cosmin.apreutesei@xxxxxxxxx
> Date: Sat, 8 Sep 2012 23:02:04 +0300
> Subject: Re: ffi initializer bit me today
> To: luajit@xxxxxxxxxxxxx
> 
> > In your first case, did you mean to say 'abc' ? For copying 3 bytes?
> 
> See, that's why I think it can lead to subtle bugs: it copies 'ab\0'.
> It's even harder to spot when you see code like this:
> 
> local cdata = ffi.new('unsigned char[?]', #s, s)
> 
> which instead should be:
> 
> local cdata = ffi.new('unsigned char[?]', #s+1, s)
> 
> The behavior is documented, just IMHO a bit inconsistent.
> 
                                          

Other related posts: