Search code examples
smalltalkvisualworks

Create a CByteArray from a CPointer in Visual Works Smalltalk


Some C function return aCPointer to a C struct. The C struct is known.
Now i want to put the C struct into a ByteArray. Basically copy the contents of the struct to a ByteArray.
In GemStone/S this can be done with:
CByteArray fromCPointer: aCPointer numBytes: 120.
"this create aCByteArray with the contents of the struct referenced by CPointer (copying only 120 bytes)"

Is there something similar on Visual Works ? I did not find it yet. It could be possible to replicate C struct at Visual Works level but is only one struct and it is ok to handle it at low level.


Solution

  • There's only the rather ugly #copyAt:to:size:startingAt: that you can send to a pointer. You need to allocate a ByteArray yourself (make sure it's big enough).

    answer := ByteArray new: size.
    pointer
            copyAt: 0
            to: answer
            size: size
            startingAt: 1.
    

    The other way (ByteArray -> Pointer) would be done using #copyAt:from:size:startingAt:.

    This method works for both ByteArray and UninterpretedBytes. If you want to read data from the bytes, UninterpretedBytes may be more helpful as you can send things like #longAt: to read a long from an offset.