C# 调用 Rust 编写的 dll 之三:传递和修改数组

C# 调用 Rust 编写的 dll 之三:传递和修改数组

文中所有的程序运行环境为:windows 10 64bit,Net 5.0,Rust 1.51;乌龙哈里 2021-05-05

C# 调用 Rust 编写的 dll 系列:

  1. 《C# 调用 Rust 编写的 dll 之一:创建 dll》
  2. 《C# 调用 Rust 编写的 dll 之二:输入输出简单数值》

下来我们来研究传递数组:

1、输入 Array

 接上两章的程序继续, rust lib.rs 添加:

#[no_mangle]//不写这个会把函数名编译成其他乱七八糟的
pub extern fn input_array(ptr:*const i32,len:usize){
    let arr=unsafe{std::slice::from_raw_parts(ptr, len)};
    println!("Rust Dll get array: {:?}",arr);
    
}

c# 调用:

        [DllImport("D:\LabRust\Learn\ln_dll\target\release\rustdll.dll",
        EntryPoint = "input_array",
        CallingConvention = CallingConvention.Cdecl)]
        public static extern void InputArray(int[] arr,uint len);
        static void TestInputArray(int[] arr,uint len)
        {
            InputArray(arr, len);
        }
        static void Main(string[] args)
        {
            int[] arr = new int[] { 1, 2, 3 };
            TestInputArray(arr, (uint)arr.Length);

            Console.WriteLine("Hello C# !");
            foreach(var a in arr)
            {
                Console.Write($"{a} ");
            }
            Console.Read();
        }

/*运行结果:
Rust Dll get array: [1, 2, 3]
Hello C# !
1 2 3
*/

这个数组传递需要确定长度,有点不方便。

2、修改数组的值:

rust lib.rs:

#[no_mangle]//不写这个会把函数名编译成其他乱七八糟的
pub extern fn modify_array(ptr:*const i32,len:usize){
    let arr=unsafe{std::slice::from_raw_parts(ptr, len)};
    println!("Rust Dll get array: {:?}",arr);
    unsafe{
        let p=ptr as *mut i32;
        p.add(0).write(4);//修改 arr[0] 的值
    }
    println!("Rust Dll modify array: {:?}",arr);
}

c# 调用:

        [DllImport("D:\LabRust\Learn\ln_dll\target\release\rustdll.dll",
        EntryPoint = "modify_array",
        CallingConvention = CallingConvention.Cdecl)]
        public static extern void ModifyArray(int[] arr, uint len);
        static void TestModifyArray(int[] arr, uint len)
        {
            ModifyArray(arr, len);
        }
        static void Main(string[] args)
        {
            int[] arr = new int[] { 1, 2, 3 };
            TestModifyArray(arr, (uint)arr.Length);
            Console.WriteLine("Hello C# !");
            foreach(var a in arr)
            {
                Console.Write($"{a} ");
            }
            Console.Read();
        }

/*输出结果为:
Rust Dll get array: [1, 2, 3]
Rust Dll modify array: [4, 2, 3]
Hello C# !
4 2 3
*/

很不错呀,很强大,只是需要确定数组的长度,不方便。

原文地址:https://www.cnblogs.com/leemano/p/14732978.html