C# reading memory allocated with AllocHGlobal with Span<T> instead of PtrToStructure?

60 Views Asked by At

I am not sure if this is even possible, but reading a lot about Span and started to play with BenchmarkDotNet and came to find out that my method is wasting a lot of memory of the heap.

I have to Interop with an external method which gives me a huge set of data. this method expects me to give a Pointer to memory to write the data to, and that is fine, I know it will use 20k of space (fixed) so I allocate memory with Marshal.AllocHGlobal(), get the IntPtr, and pass it to the external function using P/Invoke, and when done I free the memory with FreeHGlobal(), all that part is working fine and I dont expect to change anything.

Here is my dilemma, In my method, after I Invoke the external function and it writes the memory, I use Marshal.PtrToStructure() to read the results, I have defined the structure and I know where each value is, but I only care about a few of them.

I then read those values using myStruct.Whatever and assign those to my existing object, which is a managed and previously instantiated object.

I have come to discover that just by instantiating myStruct I allocate a lot of memory on the heap which after reading what I need and assign it to my other object I no longer need, and this method is executed every minute, so it turns out I am throwing to the heap more than I want to.

Is there any way I can read the memory that I already allocated with a Span and only reference to it and not create a new instance?

I was able to read byte by byte or int by int with Marshal.ReadInt but that is a lot of work and I have to remember each value offset.

0

There are 0 best solutions below