CLIDataAllocator

Last Updated on April 21, 2025 by chase

This is a C++/CLI implementation that bridges the CDataAllocator to be utilized within a C# codebase. The generic implementation exposes a particular node size, the CDataAllocator128 in this example.

The goal was to enable more direct memory management of varying types. C# however, natively has the restriction where reference types will always be associated to a GCHandle. To work with this restriction, we allocate those GCHandle as GCHandleType::Pinned. This allows us to bypass the GC process for these handles, to keep the integrity of our allocated memory. We careful track these GCHandle objects, so when we need this data we can retrieve it, and when we delete is when we will free them.

I would have enjoyed being able to expose a direct template or even generic template instead of having to expose the specific managed CDataAllocator128. However, a restriction when exposing managed types does not allow specifying the required template parameter that the native CDataAllocator requires, size_t in this case. With this restriction in mind, I worked towards minimizing implementation requirements if a different node size is needed.

The C# side is a straight forward integration once we have the CLIDataAllocator.dll dependencies in-place.

The IDataAllocator adheres to the Interface Segregation principle, allowing us to utilize the same interface for multiple allocators as required.

Here are my managed test cases, verifying: Alloc, Get, Allocated, and Delete:

Leave a Reply

Your email address will not be published. Required fields are marked *