M
Modular•12mo ago
mikegarts

Casting between DTypePointer[DType.uint8] and Pointer[UInt8] ?

Is it possible to cast between the two similar types, specifically to initialize a Pointer[UInt8] to point to the same memory addr as DTypePointer[DType.uint8]? Here is an illustration:
var ptrd = DTypePointer[DType.uint8].alloc(10)
var ptrany : Pointer[UInt8]
ptrany = ptrd # this won't work with any bitcast variant I tried...
var ptrd = DTypePointer[DType.uint8].alloc(10)
var ptrany : Pointer[UInt8]
ptrany = ptrd # this won't work with any bitcast variant I tried...
4 Replies
Alex Kirchhoff
Alex Kirchhoff•12mo ago
If you have a DTypePointer value p, you can turn it into a normal Pointer with p.address. It's not super obvious but you can find this under "Fields:" here: https://docs.modular.com/mojo/stdlib/memory/unsafe.html#dtypepointer To go the other way and create a DTypePointer from a Pointer, use the appropriate constructor, e.g. to convert a Pointer p to DTypePointer[DType.float32], use DTypePointer[DType.float32](p).
mikegarts
mikegartsOP•12mo ago
Hi @Alex Kirchhoff and thanks for the reply! I saw the .address field but couldn't make it work. For example:
var ptrd = DTypePointer[DType.uint8].alloc(10)
var ptrany : Pointer[UInt8]
ptrany = ptrd.address
var ptrd = DTypePointer[DType.uint8].alloc(10)
var ptrany : Pointer[UInt8]
ptrany = ptrd.address
yields error: cannot implicitly convert 'pointer<scalar<ui8>>' value to 'Pointer[SIMD[ui8, 1]]' in assignment I think that I'm missing something here, since the two types are quite similar (both point to a memory with UInt8). Trying to __init__ Pointer[UInt8] fails as well: ptrany = Pointer[UInt8](ptrd.address) yields: error: cannot construct 'Pointer[SIMD[ui8, 1]]' from 'pointer<scalar<ui8>>' value in assignment
Alex Kirchhoff
Alex Kirchhoff•12mo ago
Oops, good catch. The type of address actually changed in-between the last Mojo release and the unreleased version I had been looking at. So as of the next Mojo release, it should work as I described. In the mean time, I believe you should be able to use bitcast[SIMD[DType.uint8, 1]](ptrd.address). I haven't tested this since I don't have the last-released Mojo installed at this time. But this workaround should become unnecessary once the next Mojo release comes out, which I believe should be soon.
mikegarts
mikegartsOP•12mo ago
Hi @Alex Kirchhoff and thanks again. I indeed tried different ways to cast my way out, including the one you mentioned but sadly it yields in error too 🙂 error: no matching function in call to 'bitcast' with a list of bitcast variants (according to the latest docs). I guess I'll have to wait a little for the new release 🙂
Want results from more Discord servers?
Add your server