简体   繁体   中英

Execute Assembly from Pascal

How can I execute this code from Pascal :

               MOV EAX, variable1
               PUSH EBX, EAX
               MOV EAX, variable2
               POP EBX
               AND EBX, EAX

Where I define method/function arguments in function(variable1, variable2).

This is a school assignment I don't know why they are making us do Pascal/Assembly instead of Java/C++ or such.

This is not the whole assignment I did do plenty of work before I just need help with this, any help is appreciated thank you

There are basically two ways to call explicit assembly code (from any language, not just from Pascal).

The first way is to write the assembly in its own file and assemble it with your assembler. Then you would link the resulting object file with the rest of your program, and presto - your assembly function can be called. This method will require you to understand the calling convention used by your compiler, so that everything will line up at link- and runtime.

The second way is to use 'inline assembly', so called because you will write the assembly code directly in your regular language source file. You will need to use compiler-specific features to declare the assembly block and make it play nice with the compiler. This method will make your code harder to port to other compilers, but you may be able to get away without having to understand the ABI/calling convention for your system.

In general, the rules of register use (Borland pascal) in an external procedure or function are that you must preserve EDI, ESI, ESP, EBP, and EBX registers, but you can freely modify the EAX, ECX, and EDX registers.

So your asm code must look something like:

MOV EAX, variable1        //EAX := variable1          
PUSH EBX                  //save EBX
MOV EBX, variable2        //EBX := variable2        
AND EAX, EBX              //store result to EAX
POP EBX                   //restore EBX

Depend of calling convention the functions returns arguments via registers or stack. So be sure what kind of calling convention you are using.

To elaborate on GJ's answer, in Pascal/Delphi, you could wrap the whole thing up like such:

function TestAsmFunction (variable1, variable2: longword): longword; 
assembler; {<- this was neccesary in Turbo Pascal, but not in Delphi}
register; {<- it's the default calling convention anyway. So variable 1=EAX, variable2= EDX}
asm
MOV EAX, variable1        {actually unneccesary (= mov eax, eax)}
PUSH EBX                  
MOV EBX, variable2        {compiles to mov ebx, edx}
AND EAX, EBX              
POP EBX                   
end;                      {Return value is in EAX}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM