Chapter 14 - Calling C functions

This chapter discusses how to import and call various C functions.  Using printf and scanf were discussed in a previous chapters.  In general, the parameters need to be included with the call and the return value is stored in register EAX.

14.1  Rand()

 

random.asm

format PE console
include 'win32ax.inc'

;=======================================
section '.text' code readable executable
;=======================================
start:
        cinvoke time, 0
        cinvoke srand, EAX
        cinvoke rand    ;random int is returned to EAX
        mov EDX, 0
        mov EBX, 10
        idiv EBX        ;divide by 10 and put remainder in EDX
        inc EDX
        cinvoke printf, "Random number from 1-10: %d%c", EDX, 10
        invoke  Sleep,-1

;====================================
section '.idata' import data readable
;====================================
library msvcrt,'msvcrt.dll',kernel32,'kernel32.dll'
import  msvcrt,printf,'printf',rand,'rand',srand,'srand',time,'time'
import  kernel32,Sleep,'Sleep'

Output

Random number from 1-10: 10

random.cpp

#include <time.h>
#include <stdlib.h>
#include <iostream>
using namespace std;

int main()
{
    srand(time(NULL));
    int R = rand()%10 + 1;
    cout << "Random number from 1-10: " << R << endl;
    return 0;
}

Output

Random number from 1-10: 4