Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Custom Native Allocators?

Discussion in 'Burst' started by jasonboukheir, Jul 20, 2021.

  1. jasonboukheir

    jasonboukheir

    Joined:
    May 3, 2017
    Posts:
    80
    I'm working with libsodium as a native plugin. It has its own allocation and free functions for secure memory:
    sodium_malloc
    sodium_free

    I'm trying to keep my interop Burst compatible. Is there anything I should be wary of when using these native allocators?

    Is there a way I should incorporate Burst allocators and safety with these native allocators? It would be sweet to be able to clean up my sodium allocators when a Temp allocator is cleaned up for example.
     
  2. IgreygooI

    IgreygooI

    Joined:
    Mar 13, 2021
    Posts:
    48
    You probably won't need unity to create api for custom native allocators to do the job. Just make sure both side control the memory that their allocate. What you need is expose the allocator api from the native library to the csharp side.

    The best practice is probably making the struct owning sodium_malloc allocated memory implement IDisposable, and call sodium_free in dispose(), unfortunately, c sharp does not provide a language-level support to automatically insert that sweet dispose(), you have to track the memory yourself and this may be dangerous if you do not understand the behaviour of each side.

    It is possible to expose the unity allocator to the libsodium, but I am not sure if you really want to do that.
     
    Last edited: Jul 24, 2021
  3. jasonboukheir

    jasonboukheir

    Joined:
    May 3, 2017
    Posts:
    80
    I was curious if I could "hook in" to Unity's allocator so that when it is cleaned up it calls
    sodium_free
    . I don't really have a need for that though, just curious.