Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid heap allocation with native strings whenever possible #12

Open
BeanCheeseBurrito opened this issue Nov 2, 2023 · 0 comments
Open
Labels
good first issue Good for newcomers help wanted Extra attention is needed

Comments

@BeanCheeseBurrito
Copy link
Owner

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);
}
@BeanCheeseBurrito BeanCheeseBurrito added help wanted Extra attention is needed good first issue Good for newcomers labels Nov 2, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
good first issue Good for newcomers help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

1 participant