System.BadImageFormatException while calling a rust dll from netcore c# console app


I have this simple rust function.

pub extern fn add_numbers(number1: i32, number2: i32) -> i32 {
    println!("Hello from rust!");
    number1 + number2

which is compiled to dll with

name = "my_lib"
crate-type = ["dylib"]

I tried to use the dll from a C# console app (full framework), and it worked. However, when I am trying to do the same for a C# netcore console app, I am getting System.BadImageFormatException. This is what I have in the C# side

using System;
using System.Runtime.InteropServices;

namespace my_core_console
    class Program
        [DllImport(@"my_lib.dll", CallingConvention = CallingConvention.Cdecl)]
        private static extern Int32 add_numbers(Int32 number1, Int32 number2);

        static void Main(string[] args)
            var addedNumbers = add_numbers(10, 5);

along with the following project settings.

<Project Sdk="Microsoft.NET.Sdk">


    <None Remove="my_lib.dll" />

    <Content Include="my_lib.dll">


I attempted to target the x64 platform like I did for the full framework console app. However, I am still getting the following error.

Unhandled exception. System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (0x8007000B)

I am not sure what I am missing. Would appreciate any pointer.

asked on Stack Overflow Aug 27, 2020 by Sayan Pal

1 Answer


The problem is that you set the crate type to dylib not cdylib.

According to The Rust Language Reference dylib is for rust-rust dynamic linking. cdylib crates a dynamic library with the c abi for use in other programming languages.

Set crate-type to cdylib

answered on Stack Overflow Aug 27, 2020 by Nick Farley

User contributions licensed under CC BY-SA 3.0