Subject:
[ruby-ffi] Re: struct questions
From:
rogerdpack
Date:
12/19/09 10:04 PM
To:
ruby-ffi


> Then currently the only easy way to fill it is:
>
> s[:title].to_ptr.put_string(0, "foo")
>
> Thats kinda ugly, so we should have an easier syntax.
>
> I have patches that make the following work for :char/:uchar arrays:
>
> s[:title] = "foo"
> s[:title] = [ 'f'.ord, 'o'.ord, 'o'.ord ]
> s[:title] = [ 1, 2, 3]
>
> The second form also works for all other array element types.

That second one is a big scary because how does it know what the fill
the rest in? (I guess zeroes would work though).

>
> The inverse also works for :char/:uchar arrays:
>
> s[:title].to_s # => "foo"

+1

> There are a couple of corner cases that need to be figured out though.
> 1) What to do when a string + nul byte is larger than the array size
>   a) raise an error
>   b) do not terminate the string with a nul byte
>   c) truncate the string and terminate with a nul byte

vote for a

if they want b, they can do it by hand :)

>> #<SnarlStruct field1: value1, field2: value2...>
> I prefer this not happen. This would require all fields to be read, which is hardly cheap. Plus, reading a field can cause a segfault, so I'd prefer all field reads are explicit by the user.

In retrospect I agree (plus if the fields are too long, you don't want
to see them, anyway).

How about something like what rails does...
>> #<SnarlStruct (field1: type1, field2: type2, field3: type3)...>

Also another question.

When I first started using FFI::Struct's

I anticipated being able to call methods, like
a = Struct.new
a.name = "hello there"

(since that's how you access them in C, and they are certainly not
hashes).  Would a patch for such be acceptable?

> They were never designed to be subclassed, so I don't consider it a bug.

That's fine--however currently it doesn't throw any warnings or
anything if you use a subclass--it allows you to still set things like

subclass_instance[:element] = 3

then silently fails in marshalling, so I think something should could
be done to help this be less of a confusion.

-r