Flecs.NET
Flecs.NET copied to clipboard
Avoid heap allocation with native strings whenever possible
In the current API, strings that need to be passed over to the native side are always allocated on the heap with Marshal.StringToHGlobalAnsi using the NativeString helper struct.
Example:
{
string managedString = "Hello World";
using NativeString nativeString = (NativeString)managedString; // Heap allocation
random_function(nativeString); // NativeStrings are implicitly casted to byte*/sbyte*
// String is freed at the end of the scope
}
Heap allocations are unnecessary in places where strings are freed immediately after use and should be rewritten to use stack allocated memory instead.
Example:
{
string managedString = "Hello World";
byte* nativeString = stackalloc byte[managedString.Length + 1];
StackAllocString(nativeString, managedString);
random_function(nativeString);
}