Creating a Hello World library in an assembly and calling it from C #

Suppose we use NASM, as in this answer: how to write a welcome world in an assembly under windows .

I had some thoughts and questions regarding the assembly in conjunction with C # or any other .net languages.

First of all, I want to create a library that has the following function HelloWorldthat takes this parameter:

  • Name

In C #, the method signature will look like this: void HelloWorld(string name)and it will output something like

Hello World on behalf of

I searched around a bit, but I can not find a lot of good and clean material for this to start me. I know some basic assembly from more than basically gas.

Thus, any pointers in the right direction are very upset.

Summarizing

  • Create a routine in ASM (NASM) that takes one or more parameters
  • Compile and create a library of the above functions
  • Include library in any .net language
  • Call the included library function

Bonus Features

  • How to handle return values?
  • Can I write a built-in ASM method?

When creating libraries in assembly or c, you execute a certain "predefined" method, c calling convetion, right?

+5
source share
4 answers

Something like this should get a working DLL:

extern _printf

section .text
global _hello
_hello:
    push ebp
    mov ebp, esp

    mov eax, [ebp+12]
    push eax
    push helloWorld
    call _printf
    add esp, 8
    pop ebp
    ret

export _hello

helloWorld: db 'Hello world from %s', 10, 0

hello, P/Invoke. , CallingConvention Cdecl; , ANSI. , .

using System.Runtime.InteropServices;

namespace Test {
    public class Test {
        public static Main() {
            Hello("C#");
        }

        [DllImport("test.dll", EntryPoint="hello", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Ansi)]
        public static extern Hello(string from_);
    }
}
+11

, . , Hello World.

dll . , stdcall ( stdcall ) dll asm

P/Invoke.

..

asm, - , , stdout (printf c lib, , winapi )

dll #, . , , - . , ( ).

:

  • #. Managed ++.
+3

. , , , , DLL p/Invoke interops,

[DllImport("mylib.dll")]

... , , - # , CLR runtime . , CLR , , . , - , , , .

, , , eax, ebx, frames frames .., CLR-, , , . C/++:

void foo(void){
   _asm{
     xor ecx, ecx
     mov eax, 1
     ....
   }
}

CLR, , , , , CLR, , , ... Managed ++, , VB.NET/C# :

private void mycsfunction(string s){
    // Managed code ahoy
    StringBuilder sb = new StringBuilder(s);
    ......
    _asm{
        push ebp
        mov ebp, esp
        lea edx, offset sb
        ....
        mov eax, 1
        pop ebp
    }
}

, , IL- , , , 100%, , . ,

, , CLR - IL , CLR, , , ( NON-CLR), . , .

+1

, :

  • How to write a function using an assembly and put it in a DLL?
  • How do I call a function in an unmanaged DLL from managed C #?

The answer to 2 is to use P / Invoke. A lot of documentation and manuals are available in this thread. http://msdn.microsoft.com/en-us/magazine/cc164123.aspx

0
source

All Articles