【发布时间】: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)
我不确定我错过了什么。将不胜感激任何指针。
【问题讨论】:
-
考虑使用 cdylib 而不是 dylib,我猜一些缺少的依赖项会导致这种行为。 users.rust-lang.org/t/…