-3

I need a buffer of memory which holds actual objects, not references, in memory.

I am using Unity Engine for my app. In order to submit a draw-call in Unity, one must provide a Mesh-object and Material-object in the function call. Here is the part of my algorithm I am trying to optimize.

Mesh[] meshes;
Material[] materials;

Foreach (mesh-type)
  DrawMeshInstancedIndirect(mesh[i],material[i]...etc);

I want to be able to iterate over a buffer of memory directly containing the object data, with no references, because I don't want to fill my cpu cache with useless data fetching each object in random parts of memory. You cannot substitute structs for these special Unity classes.

It doesn't matter if it is bad practice or a very messy solution. This is a performance-critical part of my app where structs cannot be substitute for classes.

Here is a reference to the draw-call function, for more context.

https://docs.unity3d.com/ScriptReference/Graphics.DrawMeshInstancedIndirect.html

Tree3708
  • 33
  • 4
  • 1
    You "need" to do this? Why? This is a a very unusual "need". Feels more like an XY problem - you should provide context, as you're likely trying the wrong solution to whatever actual problem you have. – mason Jan 17 '23 at 04:10
  • I added more context. – Tree3708 Jan 17 '23 at 07:20

1 Answers1

1

Try the fixed keyword.

class Foo
{
    public int[] stuff = new int[999];

    public unsafe void ExamplePinned()
    {
        fixed (int* pStuff = stuff)
        {
//Alright, the data array is all set and ready to go. Think of 'pStuff' as a pointer 
//to the first element in the array. You can use it to access the memory of the 
//array and copy it to another buffer


        }
    }
}
jazb
  • 5,498
  • 6
  • 37
  • 44
  • PS- the `fixed` can only be used inside an `unsafe` method - also watch out for memory leaks etc – jazb Jan 17 '23 at 02:15
  • Thanks! Perhaps the phrasing of my question is bad, because I got down-voted. But I am asking if I have an array of reference-types, that are already on the heap, if its possible to move the actual object data to a new physical location, like in c++ where you can have an array of contiguous objects, not just value types. – Tree3708 Jan 17 '23 at 03:57