我有这个简单的防 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 Reference,dylib
是用于rust-rust动态链接的。 cdylib
创建带有库的动态库,以供其他编程语言使用。
将crate-type
设置为cdylib
关于c# - 从netcore C#控制台应用程序调用rust dll时发生System.BadImageFormatException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63622808/