Methods in Assembly Language

; Define a structure for rectangle
section .data
    rect:
        .width  dd 0
        .height dd 0

section .text
global _start

; Function to calculate area
area:
    ; Assuming the address of rect is in rdi
    mov eax, [rdi + rect.width]
    imul eax, [rdi + rect.height]
    ret

; Function to calculate perimeter
perim:
    ; Assuming the address of rect is in rdi
    mov eax, [rdi + rect.width]
    add eax, eax
    mov ecx, [rdi + rect.height]
    add ecx, ecx
    add eax, ecx
    ret

_start:
    ; Create a rectangle with width 10 and height 5
    mov dword [rect.width], 10
    mov dword [rect.height], 5

    ; Calculate and print area
    lea rdi, [rect]
    call area
    ; Print result (eax contains the area)
    ; (printing code omitted for brevity)

    ; Calculate and print perimeter
    lea rdi, [rect]
    call perim
    ; Print result (eax contains the perimeter)
    ; (printing code omitted for brevity)

    ; Exit the program
    mov eax, 60
    xor edi, edi
    syscall

Assembly language doesn’t have built-in support for methods or object-oriented concepts. However, we can simulate similar behavior by passing the address of our structure as the first parameter to functions.

In this example, we define a rect structure with width and height fields. The area and perim functions take the address of a rect structure in the rdi register (following the System V AMD64 ABI calling convention).

The _start function serves as our entry point, similar to the main function in higher-level languages. Here, we create a rectangle, calculate its area and perimeter, and would typically print the results (actual printing code is omitted for brevity, as it would require significant additional code in assembly).

Note that assembly doesn’t have automatic memory management or built-in print functions. In a real program, you’d need to handle memory allocation and implement or use system calls for printing output.

The example demonstrates how to work with structures and implement function-like behavior in assembly, which is analogous to methods in higher-level languages. However, the low-level nature of assembly means that many concepts have to be implemented manually or differently compared to high-level languages.