【问题标题】:System.BadImageFormatException while calling a rust dll from netcore c# console appSystem.BadImageFormatException 从 net core c# 控制台应用程序调用 rust dll
【发布时间】:2021-02-13 06:12:15
【问题描述】:

我有这个简单的 rust 函数。

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

编译成dll用

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

我尝试使用 C# 控制台应用程序(完整框架)中的 dll,并且成功了。但是,当我尝试对 C# netcore 控制台应用程序执行相同操作时,我收到System.BadImageFormatException。这就是我在 C# 方面所拥有的

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);
            Console.WriteLine(addedNumbers);
            Console.ReadLine();
        }
    }
}

以及以下项目设置。

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

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <RootNamespace>my_core_console</RootNamespace>
    <PlatformTarget>x64</PlatformTarget>
    <Platforms>x64</Platforms>
    <RuntimeIdentifier>win-x64</RuntimeIdentifier>
  </PropertyGroup>

  <ItemGroup>
    <None Remove="my_lib.dll" />
  </ItemGroup>

  <ItemGroup>
    <Content Include="my_lib.dll">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>

</Project>

我尝试以 x64 平台为目标,就像针对完整框架控制台应用程序所做的那样。但是,我仍然收到以下错误。

未处理的异常。 System.BadImageFormatException:试图加载格式不正确的程序。 (0x8007000B)

我不确定我错过了什么。将不胜感激任何指针。

【问题讨论】:

标签: c# .net-core rust interop


【解决方案1】:

问题是您将 crate 类型设置为 dylib 而不是 cdylib

根据The Rust Language Referencedylib是用于rust-rust动态链接。 cdylib 用 c abi 创建了一个动态库,用于其他编程语言。

crate-type 设置为cdylib

【讨论】:

  • 感谢您的解释。虽然我看到它必须是cdylib,但它仍然不起作用。
【解决方案2】:

我遇到了完全相同的问题。

事实证明,对于 C# 中的新控制台项目(至少对于 .NET Framework 4.7.2),默认选项是“首选 32 位代码”,这将无法运行时链接您的 x64 rust dll。

在 C# 项目中打开项目设置,构建选项卡并确保未选择“首选 32 位代码”选项:

【讨论】:

    猜你喜欢
    • 2020-04-14
    • 2020-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多