-
Hey there, I'm trying to convert the type of some memory between DynamicVector[UI8], DynamicVector[Int], and Buffer[x, UI8] and I would like to do this in a zero copy way. I'm having a hard time making it work and I would appreciate it if someone has an example on how to do this. Thanks in advance! |
Beta Was this translation helpful? Give feedback.
Answered by
sa-
May 13, 2023
Replies: 2 comments 6 replies
-
Does this work? from Vector import DynamicVector
var int_vec = DynamicVector[Int]()
int_vec.push_back(123)
print(int_vec[0]) # 123
var ui8_vec = DynamicVector[UI8](int_vec.data.bitcast[UI8](), int_vec.size)
print(ui8_vec[0]) #123 |
Beta Was this translation helpful? Give feedback.
6 replies
-
I've figured this out. Thanks to @czheo for helping me figure this out from TargetInfo import sizeof
fn reinterpret_dynamic_vector[Tsrc: AnyType, Tdest: AnyType](
src: DynamicVector[Tsrc]
) -> DynamicVector[Tdest]:
let tsrc_bitwidth = sizeof[Tsrc]()
let tdest_bitwidth = sizeof[Tdest]()
let num_bytes_src = tsrc_bitwidth * src.size
if num_bytes_src % tdest_bitwidth != 0:
print("Cannot divide up the bits for the new type")
let dest_num_elements = num_bytes_src // tdest_bitwidth
return DynamicVector[Tdest](src.data.bitcast[Tdest](), dest_num_elements)
var int_vec = DynamicVector[Int]()
int_vec.push_back(-1)
print(int_vec[0]) # output: -1
var ui8_vec = reinterpret_dynamic_vector[Int, UI8](int_vec)
print(ui8_vec.size) # output: 8
for i in range(ui8_vec.size):
print(ui8_vec[i]) # outout: 8x 255 |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
sa-
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've figured this out. Thanks to @czheo for helping me figure this out