[MacRuby-devel] Understanding Pointer objects
Laurent Sansonetti
lsansonetti at apple.com
Sun Oct 24 18:25:06 PDT 2010
Hi Caio,
On Oct 24, 2010, at 11:09 AM, Caio Chassot wrote:
> On 2010-10-24, at 05:06 , Matt Aimonetti wrote:
>
> Is there any difference if I do these instead:
>
>> pointer = Pointer.new_with_type("f")
>
> p = Pointer.new(:float) #<= new instead of new_with_type
>
>> pointer.assign(3.2)
>
> p[0] = 3.2 #<= #[]= instead of #assign
>
>
> I have used both successfully in the past. Just wondering if I was just lucky or if they're fine.
They are the same :)
> Also, what's with the #[] thing anyway? What would I get using p[1], p[2]? Is this a way to deal with C arrays or otherwise do basic pointer arithmetics?
A Pointer object allows you to allocate memory of a given type for a given number of elements. You can create an array of floats for example. Then, #[] and #[]= make sense to get/set elements of this array.
Pointer objects are also returned by MacRuby when calling a native API that returns a pointer to something. For example, float *. The API documentation might state that it's one float, or an array of floats. In this case, MacRuby doesn't really know much about the pointer itself (like its bounds), which is why using #[] and #[]= must be done in a very careful way.
Laurent
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.macosforge.org/pipermail/macruby-devel/attachments/20101024/bf1326ef/attachment.html>
More information about the MacRuby-devel
mailing list