[plt-scheme] FFI and pointer manipulations

From: Jens Axel Søgaard (jensaxel at soegaard.net)
Date: Sat Feb 10 18:09:00 EST 2007

Eli Barzilay wrote:

>On Feb  9, Jens Axel Søgaard wrote:
>>With the FFi how do I add an integer to a c-pointer?
>>More specifically I am interested in getting a pointer
>>into the middle of a byte-string.
>It's possible to do arbitrary conversions using the foreign interface,
>just like you do in C -- except that you have to put something in a
>malloced space, and reference it as something else.  No "typecast"
>function yet.  (Partly because foreign types are not completely first
>class, which is yet to be hacked.)  But:
I'm not sure, I follow. Here is an example of what I want to do:

(let ([bs (bytes 0 1 2 3 4 5)])
  (md5 <cpointer-to-bs+2> 3))

should calculate the md5 of the 3 bytes 2 3 4.

I can't figure out what to write instead of <cpointer-to-bs+2>.

>>I couldn't find anything on pointer arithmetic besides
>>ptr-equal? in the FFI manual.
>This is intentional.  Having a pointer to the middle of a malloced
>object will not work right with 3m.  In fact, I think that it may
>cause damage even if you use it in some harmless way.  One way to deal
>with this would be to provide a kind of pointer-with-offset, and
>another would be to add a new kind of "dangerous pointer" type.  Both
>will not be easy to understand and to use, and nothing is implemented
It is the pointer-with-offset I need. In my case the C code doesn't 
store the pointer, so
it ought to be safe.

Jens Axel Søgaard

Posted on the users mailing list.