NASM Forum > Using NASM

How do you detect the number of parameters passed in a macro?

(1/1)

ben321:
Lets say the macro is defined as

--- Code: ---%MACRO MyMacro 1-4
;do something
%ENDMACRO

--- End code ---

The macro can be called with 1, 2, 3, or 4 parameters. What is the syntax within the macro to detect how many parameters were actually passed to it?

fredericopissarra:
Nasmdoc 4.3.6: %0

ben321:

--- Quote from: fredericopissarra on October 07, 2022, 12:12:07 PM ---Nasmdoc 4.3.6: %0

--- End quote ---

Ok. Thanks for that. Along with another couple features I then read about in the docs, I was able to make these 2 VERY USEFUL macros.


--- Code: ---%MACRO Invoke 1-*
%ROTATE -1
%REP %0-1
push %1
%ROTATE -1
%ENDREP
call %1
%ENDMACRO



%MACRO CInvoke 1-*
%ROTATE -1
%REP %0-1
push %1
%ROTATE -1
%ENDREP
call %1
add esp,(%0-1)*4
%ENDMACRO
--- End code ---

The Invoke macro calls a function (the first parameter in the macro) followed by the remaining macro parameters which are used as the parameters of the function being called. This macro expects the called function to clean up the parameters on the stack (the StdCall calling convention). This I think is the default calling convention used by most programming languages other than C and C++.

The CInvoke macro calls a function using the calling convention used by default by C and C++ (called the CDecl calling convention). This macro works the same way as Invoke, except it expects the called function to NOT clean up the parameters on the stack, and instead the macro uses the "add esp" instruction to do the cleanup itself.

This is a HUGE improvement over having to manually use a "push" instruction for every function parameter, and having to remember to always push the parameters in REVERSE ORDER. With these macros, you supply the function parameters in the normal FORWARD ORDER. These macros take care of generating the push instructions in the reverse order for you.

This is such a significant feature added by these macros, that I've actually been waiting for a while for such functionality to be officially added to NASM itself. Unfortunately it hasn't been, which is what prompted me to make these macros.

By the way, the GoAsm assembler already has this Invoke functionality for making function calls, and it's VERY useful.

Navigation

[0] Message Index

Go to full version