微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决是否可以调用动态结构类型函数来避免 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 举报,一经查实,本站将立刻删除。