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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 |
#pragma once #include "CDataAllocator.h" #pragma managed using namespace System; using namespace System::Collections::Generic; using namespace System::Reflection; using namespace System::Runtime::InteropServices; namespace Chazix { // ----------------------------------------------------------------------------------------------- template <size_t S> public ref class CDataAllocatorManaged { private: CDataAllocatorBase<S>* m_allocator; private: ~CDataAllocatorManaged() { delete m_allocator; m_allocator = nullptr; } public: CDataAllocatorManaged(size_t nodeCount) { m_allocator = new CDataAllocatorBase<S>(nodeCount); } IntPtr Alloc(int bytes) { return IntPtr(m_allocator->Alloc(bytes)); } bool Allocated(IntPtr ptr) { return m_allocator->Allocated(ptr.ToPointer()); } void Delete(IntPtr ptr) { m_allocator->Delete(ptr.ToPointer()); } }; // ----------------------------------------------------------------------------------------------- // attribute to assign field orders when initializing an instance [AttributeUsage(AttributeTargets::Field)] public ref class FieldOrderAttribute : Attribute { private: int m_order; public: FieldOrderAttribute(int order) : m_order(order) {} const int Order() { return m_order; } }; // ----------------------------------------------------------------------------------------------- public ref class InvalidPointerException : public Exception { private: IntPtr m_ptrAddress; public: InvalidPointerException(String^ message, IntPtr ptrAddress) : Exception(message), m_ptrAddress{ ptrAddress } { } property IntPtr PtrAddr { IntPtr get() { return m_ptrAddress; } }; const int PtrValue() { if (m_ptrAddress == IntPtr::Zero) { return -1; } try { return Marshal::ReadInt32(m_ptrAddress); } catch (Exception^) { return -1; } } }; // ----------------------------------------------------------------------------------------------- // generic implementation for usage with any managed CDataAllocator ref class CDataAllocatorManagedImpl { private: Dictionary<IntPtr, List<GCHandle>^>^ m_gcHandleTracker; Func<int, IntPtr>^ m_allocateCb; Func<IntPtr, bool>^ m_isAllocatedCb; Action<IntPtr>^ m_deleteCb; private: static int SortFieldInfo(FieldInfo^ lhsField, FieldInfo^ rhsField) { auto lhsAttrs = lhsField->GetCustomAttributes(FieldOrderAttribute::typeid, false); auto rhsAttrs = rhsField->GetCustomAttributes(FieldOrderAttribute::typeid, false); FieldOrderAttribute^ lhs = lhsAttrs->Length > 0 ? safe_cast<FieldOrderAttribute^>(lhsAttrs[0]) : nullptr; FieldOrderAttribute^ rhs = rhsAttrs->Length > 0 ? safe_cast<FieldOrderAttribute^>(rhsAttrs[0]) : nullptr; int lhsOrder = lhs != nullptr ? lhs->Order() : Int32::MaxValue; int rhsOrder = rhs != nullptr ? rhs->Order() : Int32::MaxValue; return lhsOrder.CompareTo(rhsOrder); } private: // create an instance of our T object // fill out data, and attempt to utilize constructor if available generic <typename T> where T : Object T CreateInstance(IntPtr parent, ... array<Object^>^ args) { auto tid = T::typeid; if (tid->IsPrimitive && args->Length == 0) { return T(); } // if string or primitive type, and we have args, use the first arg value if ((tid == String::typeid || tid->IsPrimitive) && args->Length > 0) { return safe_cast<T>(args[0]); } T inst = Activator::CreateInstance<T>(); // we need to box the instance, because structs for example aren't able to SetValue directly through reflection, unless they're boxed Object^ boxedInst = inst; array<FieldInfo^>^ fields = tid->GetFields(BindingFlags::Public | BindingFlags::NonPublic | BindingFlags::Instance); if (fields->Length > 0) { Comparison<FieldInfo^>^ sorter = gcnew Comparison<FieldInfo^>(&CDataAllocatorManagedImpl::SortFieldInfo); Array::Sort(fields, sorter); } // iterate through the child fields to set values & create handles as necessary for (int i = 0; i < fields->Length && i < args->Length; ++i) { Object^ convertedValue = Convert::ChangeType(args[i], fields[i]->FieldType); auto cvtid = convertedValue->GetType(); fields[i]->SetValue(boxedInst, convertedValue); // c# will always manage these handles, but we want to be able to keep track of them in our allocator // ex: reference types if (cvtid->IsValueType == false) { AllocHandle(parent, fields[i]->GetValue(boxedInst)); } } return safe_cast<T>(boxedInst); } // helper function to alloc and track handles GCHandle AllocHandle(IntPtr parent, Object^ obj) { GCHandle handle = GCHandle::Alloc(obj, GCHandleType::Pinned); List<GCHandle>^ handles; if (m_gcHandleTracker->TryGetValue(parent, handles)) { handles->Add(handle); return handle; } handles = gcnew List<GCHandle>(1); handles->Add(handle); m_gcHandleTracker->Add(parent, handles); return handle; } public: CDataAllocatorManagedImpl(int size, Func<int, IntPtr>^ cbAlloc, Func<IntPtr, bool>^ cbIsAlloc, Action<IntPtr>^ cbDelete) { m_gcHandleTracker = gcnew Dictionary<IntPtr, List<GCHandle>^>(size); m_allocateCb = cbAlloc; m_isAllocatedCb = cbIsAlloc; m_deleteCb = cbDelete; } generic <typename T> where T : Object IntPtr Alloc(... array<Object^>^ args) { const int bytes = sizeof(T); void* rawBytes = m_allocateCb(bytes).ToPointer(); IntPtr ptr = IntPtr(rawBytes); auto tid = T::typeid; // create the object instance, create & fill data T obj = CreateInstance<T>(ptr, args); if (tid->IsValueType == false) { GCHandle handle = AllocHandle(ptr, obj); *(GCHandle*)rawBytes = handle; return ptr; } else if (tid->IsPrimitive && args->Length > 0) { obj = safe_cast<T>(args[0]); } Marshal::StructureToPtr<T>(obj, ptr, false); return ptr; } generic <typename T> where T : Object T Get(IntPtr ptr) { List<GCHandle>^ handles; if (m_gcHandleTracker->TryGetValue(ptr, handles) && handles != nullptr) { GCHandle handle = handles[0]; GCHandle ptrHandle = GCHandle::FromIntPtr(Marshal::ReadIntPtr(ptr)); // since m_gcHandleTracker tracks handles based off it's root ptr // => if the root ptr is a reference handle, we need to return that data directly if (ptrHandle == handle) { return safe_cast<T>(handle.Target); } } bool isAllocated = m_isAllocatedCb(ptr); if (isAllocated == false) { throw gcnew InvalidPointerException("ptr points to unallocated memory", ptr); } return Marshal::PtrToStructure<T>(ptr); } bool Allocated(IntPtr ptr) { return m_isAllocatedCb(ptr); } void Delete(IntPtr ptr) { GCHandle handle; List<GCHandle>^ handles; if (m_gcHandleTracker->TryGetValue(ptr, handles) && handles != nullptr) { for (int i = 0; i < handles->Count; ++i) { handles[i].Free(); } m_gcHandleTracker->Remove(ptr); } m_deleteCb(ptr); } }; // ----------------------------------------------------------------------------------------------- // interface to enforce implementation requirements interface class ICDataAllocatorManaged { generic <typename T> where T : Object IntPtr Alloc(... array<Object^>^ args); generic <typename T> where T : Object T Get(IntPtr ptr); bool Allocated(IntPtr ptr); void Delete(IntPtr ptr); }; // ----------------------------------------------------------------------------------------------- // managed CDataAllocator storing up to 128 bytes per node public ref class CDataAllocator128 : public CDataAllocatorManaged<128>, ICDataAllocatorManaged { private: CDataAllocatorManagedImpl^ m_impl; public: CDataAllocator128(int nodeCount) : CDataAllocatorManaged<128>(nodeCount) { m_impl = gcnew CDataAllocatorManagedImpl( 128, gcnew Func<int, IntPtr>(this, &CDataAllocatorManaged<128>::Alloc), gcnew Func<IntPtr, bool>(this, &CDataAllocatorManaged<128>::Allocated), gcnew Action<IntPtr>(this, &CDataAllocatorManaged<128>::Delete) ); } generic <typename T> where T : Object virtual IntPtr Alloc(... array<Object^>^ args) { return m_impl->Alloc<T>(args); } generic <typename T> where T : Object virtual T Get(IntPtr ptr) { return m_impl->Get<T>(ptr); } virtual bool Allocated(IntPtr ptr) { return m_impl->Allocated(ptr); } virtual void Delete(IntPtr ptr) { m_impl->Delete(ptr); } }; } |
The C# side is a straight forward integration once we have the CLIDataAllocator.dll dependencies in-place.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
namespace Chazix { internal interface IDataAllocator { public IntPtr Alloc<T>(params object[] args); public T Get<T>(IntPtr ptr); public bool Allocated(IntPtr ptr); public void Delete(IntPtr data); } internal class ManagedDataAllocator : IDataAllocator { private CDataAllocator128 m_allocator; internal ManagedDataAllocator() { m_allocator = new(1 << 8); // 256 nodes } public IntPtr Alloc<T>(params object[] args) { return m_allocator.Alloc<T>(args); } public T Get<T>(IntPtr ptr) { return m_allocator.Get<T>(ptr); } public bool Allocated(IntPtr ptr) { return m_allocator.Allocated(ptr); } public void Delete(IntPtr data) { m_allocator.Delete(data); } } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
using System.Diagnostics; using System.Runtime.Loader; namespace Chazix { internal class Program { internal struct TestAllocatedData { [Chazix.FieldOrder(0)] internal int integer; [Chazix.FieldOrder(1)] internal float rational; [Chazix.FieldOrder(2)] internal string text; } private static void Main(string[] args) { AssemblyLoadContext assemblyContext = new AssemblyLoadContext("CLIDataAllocator", isCollectible: false); try { string basePath = AppContext.BaseDirectory; string path = Path.Combine(basePath, "CLIDataAllocator.dll"); assemblyContext.LoadFromAssemblyPath(path); } catch (Exception ex) { Console.WriteLine($"DLL Load Error: {ex.Message}"); Console.WriteLine($"Inner Exception: {ex.InnerException?.Message}"); return; } ManagedDataAllocator allocator = new(); nint numberAddr = allocator.Alloc<int>(25); nint stringAddr = allocator.Alloc<string>("this is a string"); nint testDataAddr = allocator.Alloc<TestAllocatedData>(10, 23.4f, "asdfasdf"); Debug.Assert(allocator.Get<int>(numberAddr) == 25); Debug.Assert(allocator.Get<string>(stringAddr) == "this is a string"); TestAllocatedData structData = allocator.Get<TestAllocatedData>(testDataAddr); Debug.Assert(structData.integer == 10); Debug.Assert(Math.Abs(structData.rational - 23.4f) <= float.Epsilon); Debug.Assert(structData.text == "asdfasdf"); allocator.Delete(numberAddr); allocator.Delete(stringAddr); allocator.Delete(testDataAddr); Debug.Assert(allocator.Allocated(numberAddr) == false); Debug.Assert(allocator.Allocated(stringAddr) == false); Debug.Assert(allocator.Allocated(testDataAddr) == false); int emptyMem = unchecked((int)0xEEEEEEEE); try { int integer = allocator.Get<int>(numberAddr); } catch (Chazix.InvalidPointerException e) { Debug.Assert(e.PtrValue() == emptyMem); } catch (Exception e) { Console.WriteLine($"unexpected exception: {e.GetType().FullName}"); Debug.Assert(false); } try { string str = allocator.Get<string>(stringAddr); } catch (Chazix.InvalidPointerException e) { Debug.Assert(e.PtrValue() == emptyMem); } catch (Exception e) { Console.WriteLine($"unexpected exception: {e.GetType().FullName}"); Debug.Assert(false); } try { structData = allocator.Get<TestAllocatedData>(testDataAddr); } catch (Chazix.InvalidPointerException e) { Debug.Assert(e.PtrValue() == emptyMem); } catch (Exception e) { Console.WriteLine($"unexpected exception: {e.GetType().FullName}"); Debug.Assert(false); } Console.WriteLine("✓ Tests Passed"); } } } |
