c# - 从netcore C#控制台应用程序调用rust dll时发生System.BadImageFormatException

标签 c# .net-core rust interop

我有这个简单的防 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平台。但是,我仍然收到以下错误。

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


我不确定我缺少什么。将不胜感激任何指针。

最佳答案

问题是您将 crate 类型设置为dylib而不是cdylib
根据The Rust Language Referencedylib是用于rust-rust动态链接的。 cdylib创建带有库的动态库,以供其他编程语言使用。
crate-type设置为cdylib

关于c# - 从netcore C#控制台应用程序调用rust dll时发生System.BadImageFormatException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63622808/

相关文章:

rust - 如何使用Serde在反序列化期间转换字段?

javascript - Web 推送通知 'UnauthorizedRegistration' 或 'Gone' 或 'Unauthorized' - 订阅到期

c# - 依赖解析器的 Automapper IMapper 问题

c# - JetBrains Rider 带着 watch 运行

path - 如何替换PathBuf或Path的文件扩展名?

rust - Handlebars 三个阵列在一个循环中

c# - MonoRuntime 如何与 ART 共存?

c# - 将图像添加到列表框

c# - 对 bool 值使用 Interlocked.CompareExchange() 操作?

.net - .NET 核心 Ubuntu 14.04 上的 System.Net 出现问题