Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NASM - How to make array of struct pointers and access them

so my problem is this: I have struct called vertex

struc vertex
  .x  resq 1
  .y  resq 1
  .z  resq 1
endstruc

I want to make an array of pointers to the structs made of that definition. Like loading vertices form file and saving them in the structs and the pointers in the array so I can access them later. Any ideas?

The only idea I have is use something like this:

modelVertices resb vertex_size*100

Make this huge "array" of all vertices and acess it like

[modelVertices+i*vertex_size]

where i is which vertex I want to access, how would I access the vertex elements then? I am not sure now but the struct size isn't exactly just elem1_size+elem2_size... right? So I cannot access them just by adding the size of element to get to the next one no?

Is there any common way how to achieve this?

Thanks in advance and have a nice day

EDIT: I tried this

[modelVertices + vertexNumber*vertex_size + vertex.x]

To read the x of vertexNumberth vertex, I understand that assembly allows me to do almost everything with the memory so it works but is this correct usage?

like image 617
Hitokage Avatar asked Oct 25 '25 20:10

Hitokage


1 Answers

Elements of a structure are offsets from start of the structure so you can access the elements simply by adding the offset:

[modelVertices+i*vertex_size + vertex.x]

You might want to define macro for that:

%define VERTEX(i, e)  [modelVertices+i*vertex_size + vertex. %+ e]

mov VERTEX(3, y), rax     ; move rax to y of vertex at index 3

EDIT: If you want to use register as index, you must calculate the multiplication separately:

%define VERTEX(offset, e)  [modelVertices + offset + vertex. %+ e]

; calculate offset from start of the array
mov eax, vertex_size
mov edx, 3 ; index
mul edx

mov VERTEX(rax, y), rcx     ; move rcx to y of vertex at index 3

If you want to create array of pointers instead of using structures directly, you create array of qwords:

ptrArray resq 100 ; fill in the addresses somewhere

; ...

; get pointer to vertex at index i
%define VERTEX_PTR(i)   [ptrArray + i * 8]

%define VERTEX(ptr, e)  [ptr + vertex. %+ e]

mov rdx, VERTEX_PTR(3)
mov VERTEX(rdx, y), rax   ; move rax to y of vertex at index 3
like image 111
Mika Lammi Avatar answered Oct 28 '25 22:10

Mika Lammi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!