combining c++ native code & assembly

  1. speed
  2. size
  3. low-level access (registers)

First, a Word About C# and IL
Managed Code vs. Native Code IL CLR .NET class library Use ILDASM to inspect C# MANAGED code =>IL - Run the the Visual Studio command prompt - type in ILDASM - choose a C# exe file References: msdn: ildasm a nice IL C# tutor

C++ Code

Mixed Code: __asm Blocks in C++
__asm { assembly code } The __asm (2 underscores!) keyword invokes the inline assembler and can appear wherever a C++ statement is legal and must be followed by an assembly instruction or a group of assembly instructions in braces. The inline assembler lets you embed assembly-language instructions in your C and C++ source programs. It's built into the compiler, so you don't need a separate assembler . Inline assembly code can use any C or C++ variable or function name that is in scope, so it's easy to integrate with your program's C and C++ code. Because the assembly code can be mixed with C and C++ statements, it can do tasks that are cumbersome or impossible in C or C++ alone. Example Code: ============= __asm { mov al, 2 mov dx, 0xD007 out dx, al } OR, you can put __asm before each assembly instruction: __asm mov al, 2 __asm mov dx, 0xD007 __asm out dx, al
Can NOT use assembler directives including data defintions. Can only use registers and variables declared in C++.
Example Program: ================ add 3 to 9 equals 12 (in EAX) subtract 2 getting 10 (in EAX) negate giving -10 (EAX) move into C++ variable, number print the variable (-10) #include <iostream> using namespace std; int main() { int number=3; __asm { mov EAX, 00000009h add EAX, number ; add 3 mov EBX, 2 sub EAX, EBX ; 12 - 2 = 10 neg EAX mov number, EAX } cout << number; ; -10 return 0; }
Example Program: ================ #include <iostream> using namespace std; int Sum(int, int); int main() { cout << "Hello \n\n"; int x = Sum( 3, 4 ); cout << x << endl; // 7 cout << Sum( 3, 2 ) << endl; // 5 cout << Sum( Sum( 1,2 ), x ) << endl; //10 return 0; } int Sum (int x, int y) { int s; __asm { mov eax, x mov ebx, y add eax, ebx mov s, eax } return s; }