是否可以调用动态结构类型函数来避免 gc?

问题描述

我尝试调用一个未知结构类型的函数来避免 gc,如下所示

using System;
using System.Runtime.InteropServices;
using System.Reflection;

namespace Shark
{
    unsafe class Program
    {
        public delegate void* Work(void* instance);
        public delegate Vector2 WorkArr(void* instance);
        
        static void Main(string[] args)
        {
            Vector2 value = new Vector2(10,10,10);
            MethodInfo method = typeof(Vector2).getmethod("F");
            Work function = Marshal.GetDelegateForFunctionPointer<Work>(method.MethodHandle.GetFunctionPointer());

            void* pt = function(&value);// cause error "read/write protected memory..."
        }
    }

    public struct Vector2 {
        public int x;
        public int y;
        public int z;
        public Vector2(int x,int y,int z) {
            this.x = x;
            this.y = y;
            this.z = z;
        }
        public Vector2 F() {
            return new Vector2(50,50,50);
        }
        public void Show() {
            Console.WriteLine($"{x},{y},{z}");
        }
    }
}

函数返回内存大小小于或等于8的struct类型时有效,但当内存大小大于8时失败。 那么有没有办法做到这一点?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)