Skip to content
Systems programming for what’s next.
— Vex

Foreign types and ownership ​

Foreign handles and pointers have contracts defined by the foreign library, not just by a Vex type. A binding must specify nullability, valid lifetime, who closes the handle, the matching allocator/destructor, thread and reentrancy rules, and the error paths. Do not infer those facts from a raw pointer alone.

Choose one owner and one cleanup path ​

  • Caller-owned handle: after successful creation, arrange for the matching foreign destructor to run exactly once. On creation failure, do not destroy a null or uninitialized handle unless the foreign API explicitly permits it.
  • Foreign-owned handle: the application borrows it only while the foreign owner guarantees validity. The application must not free it. Synchronize invalidation and callbacks according to the foreign library's rules.
  • Transferred handle: agree on the precise transfer point and what happens when the operation fails. A pointer crossing a boundary does not by itself establish a transfer.

Do not combine explicit cleanup with automatic drop unless the documented ownership contract proves that only one path can perform destruction. A defer and automatic destruction can otherwise release the same handle twice. See First native bridge for a tested .vxc/.vx example with explicit cleanup and counters on success and error paths.

Design the boundary around ownership ​

User-package foreign declarations belong in a .vxc boundary. Keep the raw handle and the matching foreign operations together, then give the public Vex wrapper an explicit ownership contract:

Foreign operationContract to expose in the wrapper
Create or openSuccess produces one owned handle; failure produces no usable handle
Read or inspectBorrows the handle; any returned pointer states which owner keeps it alive
Register a callbackStates who retains the callback and when registration is released
Transfer or adoptConsumes ownership at a defined success point; defines ownership on failure
Close or destroyReleases an owned live handle once using the matching foreign function

For example, an image wrapper may own the image handle while a pixel view borrows its storage. Destroying or resizing the image invalidates that view. Returning copied pixel data creates an independent owner; returning the raw address does not. An error result from an operation must also state whether the original handle remains usable.

Use defer for an explicit cleanup path when the handle remains in one scope. If a wrapper provides automatic destruction, transfer that responsibility along with the wrapper and avoid a second explicit destroy. See First native bridge for complete .vxc and .vx code, FFI for declarations, and Unsafe for raw access obligations.

Released under the MIT License.