Subject:
[ruby-ffi] Re: initialize :strings in structs
From:
Evan Phoenix
Date:
8/26/09 4:50 PM
To:
ruby-ffi




On Aug 21, 4:40 pm, Wayne Meissner <wmeiss...@gmail.com> wrote:
> Its a Ruby FFI problem.
>
> The problem is that to set a string in a C struct (which is just a
> pointer to some native memory), you need to allocate & manage the
> deallocation of native memory.  Automatically managing the
> deallocation so the memory is not freed prematurely (and crashing the
> VM), nor kept indefinitely (a memory leak) is a bit tricky, so we
> punted on it and pushed that back up to the FFI API user.
>
> So, to be able to set string fields, you need to declare them as
> :pointer, and manage the memory yourself via a MemoryPointer, or
> mapping in malloc()/free() and using them.
>
> Thats no exactly convenient, but for now, its what you have to do.
>
> Note: JRuby works around this by attaching the string memory ownership
> to the Struct ruby instance.  I'm not exactly sure if this is the best
> way to do it, since it hides the allocation/deallocation in a
> potentially dangerous way - when the ruby object gets collected, the
> memory gets freed, and if that struct got passed to native code that
> kept references to the strings, then that memory gets freed, and the
> next time the native code accesses those memory locations, everything
> goes *boom*, and its hard to figure out why.

The JRuby special case should probably be removed, since it lets
people write FFI code that works on JRuby, but not anywhere else.
You've hit the nail on the head, the problem isn't solvable except by
the user, so all implementations need to delegate to the FFI user to
solve this.

 - Evan

>
> 2009/8/22 Jan <jan.ber...@gmail.com>:
>
>
>
>
>
> > hey all,
>
> > is it possible (with NiceFFI) to initialize strings inside a struct?
> > e.g.
>
> > class Config < NiceFFI::Struct
> >    layout(:api_version, :int,
> >      :cache_location, :string
> >      :settings_location, :string
> >   )
>
> > Config.new(:api_version=>1, :cache_location=>"/tmp")
>
> > I get
>
> > /Library/Ruby/Gems/1.8/gems/nice-ffi-0.1/lib/nice-ffi/nicestruct.rb:
> > 380:in `[]=': Cannot set :string fields (ArgumentError)
>
> > is this a problem with FFI in general or could support for this added?
>
> >  thanks,
>
> >   jan