我正在尝试从我在 VB.net WPF 项目中从 Rust 创建的 DLL 调用函数,但收到“System.Runtime.InteropServices.MarshalDirectiveException:'PInvoke 限制:无法返回变体。'”错误。
关于如何解决这个问题有什么建议吗?我一直在用这个把头撞在墙上。
下面是创建界面的每个部分的相关代码段(VB.net、Rust、C#)。
流量:
这是代码:
锈面:
use interoptopus::{ffi_function, ffi_type, Inventory, InventoryBuilder, function};
#[ffi_function]
#[no_mangle]
pub extern "C" fn testfunc() {
println!("message: {}", hello_string(""));
}
fn hello_string(x: &str) -> &str {
return "hello world";
}
pub fn my_inventory() -> Inventory {
InventoryBuilder::new()
.register(function!(testfunc))
.inventory()
}
创建与 Rust 的 c# 互操作:
use interoptopus::util::NamespaceMappings;
use interoptopus::{Error, Interop};
use std::fs;
use std::path::Path;
#[test]
fn bindings_csharp() -> Result<(), Error> {
use interoptopus_backend_csharp::{Config, Generator};
use interoptopus_backend_csharp::overloads::{DotNet, Unity};
let config = Config {
dll_name: "testCustomDLL".to_string(),
namespace_mappings: NamespaceMappings::new("testCustomDLL"),
..Config::default()
};
Generator::new(config, testCustomDLL::my_inventory())
.add_overload_writer(DotNet::new())
//.add_overload_writer(Unity::new())
.write_file("bindings/testCustomDLL.cs")?;
Ok(())
}
这是生成的 Interop 代码,编译为 DLL 并被主要解决方案引用:
// Automatically generated by Interoptopus.
#pragma warning disable 0105
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using testCustomDLL;
#pragma warning restore 0105
namespace testCustomDLL
{
public static partial class Interop
{
public const string NativeLib = "testCustomDLL";
static Interop()
{
}
[DllImport(NativeLib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "testfunc")]
public static extern void testfunc();
}
public class InteropException<T> : Exception
{
public T Error { get; private set; }
public InteropException(T error): base($"Something went wrong: {error}")
{
Error = error;
}
}
}
添加Rust功能的VB.net类:
Imports System.Runtime.InteropServices
Namespace classes
Public Class NativeMethods
<DllImport(".\dependencies\testCustomDLL.dll")>
Public Shared Function testfunc()
End Function
End Class
End Namespace
调用Rust函数的VB.net代码,导致错误:
Private Sub B_code_Click(sender As Object, e As RoutedEventArgs) Handles B_code.Click
classes.NativeMethods.testfunc()
End Sub
最终目标是将一个字符串从 VB.net 传递给 Rust DLL,对其进行操作,然后将其返回给 VB.net。