简体   繁体   English

如何返回从 Rust 到 C# 的整数数组?

[英]How to return an array of integers from Rust to C#?

I'm trying to use this Rust function in C#:我正在尝试在 C# 中使用这个 Rust function:

pub extern fn get_possible_moves(i: i8, j: i8, k: i8) -> [i8; 512]

I wrote this signature in the C# code:我在 C# 代码中写了这个签名:

[DllImport("my_library")]
private static extern sbyte[] get_possible_moves(sbyte i, sbyte j, sbyte k);

This doesn't work:这不起作用:

Unhandled exception. System.Runtime.InteropServices.MarshalDirectiveException: Cannot marshal 'return value': Invalid managed/unmanaged type combination.

Is the method signature incorrect?方法签名不正确吗?

Assuming Rust exports a C-style array, the marshaler would not be able to convert it to a managed array since it does not know the length.假设 Rust 导出 C 样式数组,编组器将无法将其转换为托管数组,因为它不知道长度。 There seem to be two options:似乎有两种选择:

  • Add an attribute to tell the marshaler how long the array is : [MarshalAs(UnmanagedType.LPArray, SizeConst=512)]添加一个属性来告诉编组器数组的长度[MarshalAs(UnmanagedType.LPArray, SizeConst=512)]
  • Change the return type to an IntPtr and convert it to an array by hand.将返回类型更改为IntPtr并手动将其转换为数组。 See ToPointer .请参阅ToPointer Keep in mind that the returned memory might need to be de-allocated, somehow.请记住,返回的 memory 可能需要以某种方式解除分配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM