Search This Blog

Friday, July 5, 2013

Using assembler in C#

The only one easy way to do that is the following:

1) to create some dll  in C++ which contains assembler code.

// Somename.cpp

#include "SysInfo.h"

BOOL __stdcall DllMain(HINSTANCE hInst, DWORD dwReason, LPVOID lpReserved) {
 return  TRUE;
}
//write some functions in C
extern "C" __declspec(dllexport) int __stdcall someFunction() {
 int retVal;
         //write some C code
 // write some code in assembler
_asm { mov eax, 1 mov retVal, eax } // return result return (retVal)
//write some other functions in C
2)to use dumpbin tool in order to get thwe right name of the Function. Something like that:                             dumpbin -exports Somename.dll    in order to get some output like the following:         ordinal hint RVA name
          1    0 00001005 ?someFunction@@YGXPAD@Z
The Compiler in order to prepare functionw for overloading gives to functions new names,
This step can be ommited if you use the extern "C" keyward . In this manner the C compiler is informed to don't decorate the function name.
Here @ shows the function uses the standard calling convention stdcall

stdcall

The stdcall calling convention is a variation on the Pascal calling convention in which the callee is responsible for cleaning up the stack, but the parameters are pushed onto the stack in right-to-left order, as in the _cdecl calling convention. Registers EAX, ECX, and EDX are designated for use within the function. Return values are stored in the EAX register.

stdcall is the standard calling convention for the Microsoft Win32 API and for Open Watcom C++.
more about calling conventions here 3)to call functions in dll  through some C# program
/ Main.cs


using System;
using System.Runtime.InteropServices;

class MainClass {
 [DllImport("Somename.dll")]
 static extern int someFunction();
 
 
 // main program
 public static void Main() {
  
  //get  someFunction() result

  try {
   int param = someFunction();
   Console.WriteLine("Param value = {0}", param .ToString()                    );
  }
  catch (DllNotFoundException e) {
   Console.WriteLine(e.ToString());
  }
  catch (EntryPointNotFoundException e) {
   Console.WriteLine(e.ToString());
  }
  
  
 }
};

No comments:

Post a Comment

About Me

An seasoned developer, architect and with some Team Leading exposure, offering full project life cycle experiences within multi cultural, multi National environments and within differing business streams and all primarily on a .Net platform.