You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I'm building a wrapper for a C library and have a question on the recommended design patterns. The library I'm wrapping contains several functions that allocate memory for a structure and return a pointer to it. This pointer is then used to perform operations on the structure. I want to have an associated V structure for the C structure, but I'm not sure what is the best way to deal with the pointer.
My first thought was to include the pointer in the structure and to provide a release method to clear it:
This is simple, but it introduces different possibilities for memory corruption (use after free, double free, ...). My second thought was tracking the state of the C structure only within the V structure and only creating the C structure on demand. This would prevent storing pointers, but causes additional overhead with allocations and state tracking.
A third option would be to use V's autofree mechanism. The release method from above could be kept private to force MyStruct to have a valid pointer as long as it exists. But according to the documentation usage of autofree is not recommended yet.
So, what is the best design for this kind of problem? I'm looking forward to some good suggestions 🙂
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Hi all 👋
I'm building a wrapper for a C library and have a question on the recommended design patterns. The library I'm wrapping contains several functions that allocate memory for a structure and return a pointer to it. This pointer is then used to perform operations on the structure. I want to have an associated V structure for the C structure, but I'm not sure what is the best way to deal with the pointer.
My first thought was to include the pointer in the structure and to provide a
release
method to clear it:This is simple, but it introduces different possibilities for memory corruption (use after free, double free, ...). My second thought was tracking the state of the C structure only within the V structure and only creating the C structure on demand. This would prevent storing pointers, but causes additional overhead with allocations and state tracking.
A third option would be to use V's autofree mechanism. The
release
method from above could be kept private to forceMyStruct
to have a valid pointer as long as it exists. But according to the documentation usage of autofree is not recommended yet.So, what is the best design for this kind of problem? I'm looking forward to some good suggestions 🙂
Beta Was this translation helpful? Give feedback.
All reactions