views:

190

answers:

2

I'm trying to inline some assembly code in my C code:

__asm { mov reg,val };

The problem: I want to define the register and value dynamically. I know the 'val' can be a variable written in the C code, but I don't know how can I choose the register dynamically (i.e decide according to user input- register 'dh' or 'dl').

Any suggestions?

+4  A: 

Use an enum and switch in the C-code:

typedef enum
{
  R_AL,
  R_AH,
  R_AX,
  R_EAX,
...
} REGS;
...
REGS nReg;
...
switch (nReg)
{
    case R_AL: __asm { mov al,val } break;    
    case R_AH: __asm { mov ah,val } break;    
    case R_AX: __asm { mov ax,val } break;
    ...
}
slashmais
+4  A: 

Well ... That would require you to modify the code at run-time.

The __asm { } construct happens all at compile-time, so you can't affect its contents later.

Of course, self-modifying code is not exactly what modern operating systems are set up to do most easy, so you're going to have to jump through a few hoops (cache flushing, code being in non-writable segments, and so on).

Update: Of course you might be able to use slashmais's technique and switch between a set of pre-compiled versions, but I'd be scared about mixing code at that level (register clobbering comes to mind).

unwind