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:
4 Replies
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).Modular Docs - unsafe
Module
Hi @Alex Kirchhoff and thanks for the reply!
I saw the .address field but couldn't make it work. For example:
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 assignmentOops, 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.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 🙂