Author Topic: How do you detect the number of parameters passed in a macro?  (Read 291 times)

Offline ben321

  • Full Member
  • **
  • Posts: 133
How do you detect the number of parameters passed in a macro?
« on: October 07, 2022, 04:55:52 AM »
Lets say the macro is defined as
Code: [Select]
%MACRO MyMacro 1-4
;do something
%ENDMACRO

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?

Offline fredericopissarra

  • Full Member
  • **
  • Posts: 228
  • Country: br
Re: How do you detect the number of parameters passed in a macro?
« Reply #1 on: October 07, 2022, 12:12:07 PM »
Nasmdoc 4.3.6: %0

Offline ben321

  • Full Member
  • **
  • Posts: 133
Re: How do you detect the number of parameters passed in a macro?
« Reply #2 on: October 07, 2022, 08:42:45 PM »
Nasmdoc 4.3.6: %0

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: [Select]
%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

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.
« Last Edit: October 07, 2022, 08:45:57 PM by ben321 »