C# 可以调用动态结构类型函数来避免gc吗?

C# 可以调用动态结构类型函数来避免gc吗?,c#,memory-management,garbage-collection,function-pointers,C#,Memory Management,Garbage Collection,Function Pointers,我试图调用一个未知结构类型的函数来避免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

我试图调用一个未知结构类型的函数来避免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}");
        }
    }
}
使用系统;
使用System.Runtime.InteropServices;
运用系统反思;
名称空间鲨鱼
{
不安全类程序
{
公共委托无效*工作(无效*实例);
公共委托向量2工作arr(void*实例);
静态void Main(字符串[]参数)
{
Vector2值=新的Vector2(10,10,10);
MethodInfo method=typeof(Vector2).GetMethod(“F”);
工作函数=Marshal.GetDelegateForFunctionPointer(method.MethodHandle.GetFunctionPointer());
void*pt=函数(&value);//导致错误“读/写保护内存…”
}
}
公共结构向量2{
公共int x;
公共智力;
公共INTZ;
公共向量2(整数x,整数y,整数z){
这个.x=x;
这个。y=y;
这个。z=z;
}
公共向量2f(){
返回新矢量2(50,50,50);
}
公开展览({
WriteLine($“{x},{y},{z}”);
}
}
}
当函数返回内存大小小于或等于8的结构类型时,该函数起作用,但当内存大小大于8时,该函数失败。
那么有什么方法可以做到这一点吗?

没有,没有,除非您将struct方法定义为
静态void Show(Vector2*实例)
,然后通过
固定的
指针。如果没有
fixed
,则不应将托管指针转换为非托管指针。