[racket] using s16vector-set! on malloc'ed values

From: John Clements (clements at brinckerhoff.org)
Date: Fri Oct 25 17:44:50 EDT 2013

On Oct 25, 2013, at 2:42 PM, Matthew Flatt wrote:

> At Fri, 25 Oct 2013 14:28:13 -0700, John Clements wrote:
>> Unsafe-s16vector-set! is *MUCH* faster than ptr-set!.  About 10x faster, 
>> apparently. 
>> 
>> In the rsound package, I want to use unsafe-s16vector-set! on a region of 
>> memory that's allocated by malloc--or, more specifically, the malloc 
>> associated with a dll, because windows cares about things like this.
>> 
>> Here's some code that doesn't work:
>> 
>> #lang racket
>> 
>> (require ffi/unsafe
>>         ffi/vector)
>> 
>> (define ptr (malloc 1000))
>> 
>> (s16vector-set! ptr 0 2244)
>> 
>> In fact, it causes a seg fault.
> 
> The program above gives
> 
> s16vector-set!: expected argument of type <s16vector>; given: #<cpointer>
> 
> but if you use `unsafe-s16vector-set!` (as suggested further above),
> then you're likely to get a seg fault.
> 
> 
>> If I understand correctly, this is because this is taking the "pointer 
>> value"--probably an 8-byte or 16-byte structure that holds a pointer--and 
>> treats it like it's a massive s16vector.
> 
> Not quite. Both a plain pointer and an `s16vector` value are
> represented as a wrapper that points to the actual array, but the
> pointer is in a slightly different place inside each kind of wrapper.
> 
> 
> Using `cast` to convert from a raw pointer to an `_s16vector`
> effectively converts the wrapper:
> 
> (define ptr (cast (malloc 1000)
>                   _pointer
>                   (_s16vector o 500)))
> 

D'oh! There's an _s16vector type known to Racket. I knew it would be something simple.

Many thanks for the help!

John



Posted on the users mailing list.