Inline Assembly

information about SharpBASIC language elements
Post Reply
User avatar
Site Admin
Posts: 51
Joined: Sun Nov 21, 2021 12:04 pm
Location: Netherlands

Inline Assembly

Post by frank »

SharpBASIC supports inline assembly code written in NASM (Netwide Assembler), which is also used by the compiler as back-end. To include assembly code, use the keyword asm followed by a do .. end; block:

Code: Select all

asm do
  ' ...
SharpBASIC identifiers can be used inside assembly code blocks. Hexadecimal numbers can be used as well, but currently only in SharpBASIC notation, e.g. #hFF

The following inline assembly example is from the SharpBASIC system library and copies a block of memory. Note that inside assembly code blocks, comments start with a semicolon.

Code: Select all

' ----------------------------------------------------------------------------
' ----------------------------------------------------------------------------
' copy a memory block
' _saddr: source address
' _daddr: destination address
' _len: length in bytes to be copied
' ----------------------------------------------------------------------------
sub cpmem(_saddr: ptr, _daddr: ptr, _len: uint)
  asm do
    push     esi
    push     edi
    push     eax
    push     ecx

    mov      ecx, [_len]           ; length
    cmp      ecx, #h0              ; larger than 0 ?
    jle     .__out

    mov      esi, [_saddr]         ; source
    mov      edi, [_daddr]         ; destination

    mov      al, [esi]             ; from source
    mov      [edi], al             ; to destination
    inc      esi                   ; increment pointers
    inc      edi
    dec      ecx                   ; decrement counter

    cmp      ecx, #h0              ; done?
    jne      .__copy

    pop      ecx
    pop      eax
    pop      edi
    pop      esi
Important note: When taking the address of an identifier inside a subroutine or function, don't use the mov instruction! Use the lea instruction instead, so:

Code: Select all

mov     esi, _local_var       ; NOT ok
lea     esi, [_local_var]     ; OK
Keep in mind that no registers are preserved when setting up an inline assembly code block.
Last edited by frank on Wed Mar 09, 2022 2:47 pm, edited 3 times in total.
Keep it simple!
Post Reply