C#C
C#3y ago
Bambosa

❔ P/Invoke x86 ASM

I have the following x86 assembly function:

section .text
    global _add
    _add:
        ; Arguments are in the registers: rcx and rdx
        
        mov rax, rcx    ; Move the first argument from rcx to rax
        add rax, rdx    ; Add the second argument from rdx to rax
        
        ret             ; Return


I am compiling it into a win64 dll using NASM: nasm -f win64 maths.asm -o maths.dll

The consuming project is set to 64 bit:
<PropertyGroup>
    <TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
    <Platforms>x64</Platforms>
</PropertyGroup>


Bindings in C#:
public static partial class Maths
{
    [LibraryImport(Native.Maths)]
    [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })]
    private static partial int add(int a, int b);
    
    public static int Add(int a, int b) => add(a, b);
}


Unhandled exception. System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (0x8007000B)
   at Native.Maths.add(Int32 a, Int32 b)
   at Native.Maths.Add(Int32 a, Int32 b) in D:\Code\C#\AssemblyTest\Native\Maths.cs:line 12
   at Program.<Main>$(String[] args) in D:\Code\C#\AssemblyTest\Managed\Program.cs:line 3


Does anyone have any idea what format this should be in for the runtime to accept, I assumed using the same platform architecture and CDECL calling conventions would be enough for this to work.

Thanks
Was this page helpful?