[racket] make-sized-byte-string and GC

From: Roman Klochkov (kalimehtar at mail.ru)
Date: Sat Jan 25 15:08:09 EST 2014

 So, to make string, that is freed by reciever, I should make something like

(define _string/transfer 
       (make-ctype _bytes
                        (λ (v) 
                          (define b (if (string? v) (string->bytes/utf-8 v) v))
                          (define length (bytes-length b))
                          (define res (malloc 'raw length))
                          (memcpy res b length))                         (λ (v) (register-finalizer v free))))

Or finalizer will not work (because v is _pointer, but the type returns _bytes), and instead I have to make
(λ (v)
   (define res (cast v _pointer _bytes))
   (register-finalizer v free))

?


Суббота, 25 января 2014, 14:37 -05:00 от Ryan Culpepper <ryanc at ccs.neu.edu>:
>On 01/25/2014 01:28 PM, Roman Klochkov wrote:
>> Is making bytestring from pointer adds the pointer to GC?
>> 
>>
>>  > (define x (malloc 'raw 10))
>>  > x
>> #<cpointer>
>>  > (define b (make-sized-byte-string x 10))
>>  > (cpointer-gcable? b)
>> #t
>>  > (cpointer-gcable? x)
>> #f
>>  > (cast x _pointer _int32)
>> 173726656
>>  > (cast b _pointer _int32)
>> 173726656
>>
>> So b and x points to the same block of 10 bytes, but value of b is
>> GCable and value of x is not.
>> I assume, that when b will be changed, then the bytestring will be
>> collected and accessing x will give segfault. Am I right?
>
>I think it's a bug that (cpointer-gcable? b) returns true, since the FFI 
>generally treats bytestrings as pointers to the memory that stores their 
>contents, and in this case that memory is not managed by the GC.
>
>The bytestring object itself (which consists of a header, a pointer, and 
>a length, IIRC) is collectible, but then so is the cpointer object 
>(which consists of a header, a pointer, and some other stuff, like a tag 
>list).
>
>So no, you should not expect a segfault. On the other hand, if you free 
>x and use b afterwards, then you should expect a segfault or some other 
>form of memory corruption.
>
>Ryan
>


-- 
Roman Klochkov
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20140126/2fceafdd/attachment.html>

Posted on the users mailing list.