Safe Encapsulation of FFI
The biggest risk in calling C code lies in pointer operations and memory management. Cangjie's CPointer provides an isNull() method to check for null pointers, which should always be called before dereferencing. By encapsulating unsafe operations inside safe functions, you can minimize the scope of unsafe code.
Memory allocated on the C side (such as via malloc) must be freed by the C side (such as via free) and cannot be managed by Cangjie's garbage collector. Similarly, Cangjie-side objects cannot be passed to C code to hold pointers (CPointer is only valid during function calls). Following the "who allocates, who frees" principle is key to avoiding memory leaks and dangling pointers.
The code on the right demonstrates the safe encapsulation pattern: the safeAlloc function internally handles all unsafe operations, including null pointer checks, memory write/read operations, and timely deallocation. External callers only see a clean, safe interface.
unsafe blocks should be as small as possible. Encapsulating unsafe operations inside functions and only exposing safe interfaces is good programming practice.Try modifying the safeAlloc function to return an Option type, returning None when allocation fails.