首页 > 解决方案 > 是否可以调用避免 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 的结构类型时,它可以工作,但当内存大小大于 8 时会失败。那么有什么办法可以做到这一点?

标签: c#memory-managementgarbage-collectionfunction-pointers

解决方案


推荐阅读