简体   繁体   中英

How to store a function into a variable in MIPS assembly

int compare(int x, int y){
if (x < y)
return 1;
else
return 0;
}

How would I be able to store this into a variable to call back to as a function to use in MIPS assembly language? say I want to make h = compare(n[g], m[d]);

Neither C nor assembly have lambdas for free. So instead, write another function. Suggest getting it working in C first, then can take to assembly — maybe start with something like this:

int hh ( int *n, int g, int *m, int d ) {
    return compare ( n[g], m[d] );
}

With that you can do h = hh if that's what you want, and you can invoke h ( someN, someG, someM, someD ) .

This translates to assembly fairly literally. h would be a function pointer, and hh is a label, so simply obtain address of hh and store in h .

To invoke, get value of function pointer h into a non-parameter register like $t0 while also establishing parameters, and then use jalr as in jalr $t0 to invoke the function pointer.


If what you want to make a closure with variables captured that will be a bit more complicated since you'll need some storage to hold the captured variables and a protocol to bind the function and the data, and then to invoke the closure function on that data.

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