[gambit-list] Returning a byte array from C

Mikael mikael.rcv at gmail.com
Wed Sep 25 05:27:19 EDT 2013

Hi Vijay,

Looks good.

A possible improvement is to drop the malloc() call you do and just read()
straight into ___BODY(data_vect) , this saves you a round of copying too,
and is also in some limited sense safer as there's no malloc() that could
return NULL anymore.

Last note would be that at the time SMP is released, every access out there
of the Scheme heap from C calls such as ___BODY() will need to be gone
through as then, I suppose, unlike now, GC:s could happen also during FFI
calls - my best understanding is that the primary solution will be using
___STILL objects only. Interestingly enough, this is what |make-u8vector|
makes already today, for u8vectors bigger than ___MSECTION_BIGGEST ,
however that logic is not a lot to be relied on so I guess it'll be
relevant to implement a |make-still-u8vector| or alike then.


2013/9/25 Vijay Mathew <vijay.the.lisper at gmail.com>

> Hi,
> Thanks for reviewing my code.
> I have updated the C function as follows:
> int read_bytes (int fd, size_t count, ___SCMOBJ data_vect)
>  {
>    void *data = malloc (count);
>    int result;
>    if (data == NULL)
>      result = -1;
>    else
>      {
>        result = read (fd, data, count);
>        if (result > 0)
>          memcpy (___BODY (data_vect), data, result);
>        free (data);
>      }
>    return result;
>  }
> A call from scheme will look like:
> (read-bytes fd count (make-u8vector count 0))
> I suppose now I don't have to worry about leaks or
> heap-overflow-exceptions.
> Thanks,
> --Vijay
> On Tue, Sep 24, 2013 at 8:52 PM, Marc Feeley <feeley at iro.umontreal.ca>wrote:
>> On 2013-09-23, at 11:14 AM, Vijay Mathew <vijay.the.lisper at gmail.com>
>> wrote:
>> > The following C function is a wrapper for the `read' system call.
>> > It returns a pair that contains the number of bytes read and the data.
>> > Is this the right way to initialize a u8vector from C?
>> There are a few things I would do differently, such as heap overflow
>> checking.  But for the particular task of providing a wrapper to the read
>> system call I would use a different interface.  Why don't you allocate the
>> buffer in Scheme before calling read?  That would simplify the C code
>> (avoiding GC issues) and would be more efficient.
>> Marc
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mailman.iro.umontreal.ca/pipermail/gambit-list/attachments/20130925/ad70a145/attachment.htm>

More information about the Gambit-list mailing list