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

.net, assembly, c#, inline-assembly, vb.net

Solution

Something like this should get you 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

You then just need to call the 'hello' function using P/Invoke. It doesn't clean up after itself, so you need to set CallingConvention to Cdecl; you also need to tell it you're using ANSI strings. Untested, but it should work fine.

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_);
    }
}

Problem

Let's say we use NASM as they do in this answer: how to write hellow world in assembly under windows. I got a couple of thoughts and questions regarding assembly combined with c# or any other .net languages for that matter. First of all I want to be able to create a library that has the following function `HelloWorld` that takes this parameter: - Name In C# the method signature would looke like this: `void HelloWorld(string name)` and it would print out something like Hello World from name I've searched around a bit but can't find that much good and clean material for this to get me started. I know some basic assembly from before mostly `gas`though. So any pointers in the right direction is very much apprechiated. To sum it up - Create a routine in ASM ( NASM ) that takes one or more parameters - Compile and create a library of the above functionality - Include the library in any .net language - Call the included library function Bonus features - How does one handle returned values? - Is it possible to write the ASM-method inline? When creating libraries in assembly or c, you do follow a certain "pre defined" way, the c calling convetion, correct?

Original source

Related problems