1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
// Copyright 2026 Adobe. All rights reserved.
// This file is licensed to you under the Apache License,
// Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
// or the MIT license (http://opensource.org/licenses/MIT),
// at your option.
// Unless required by applicable law or agreed to in writing,
// this software is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
// implied. See the LICENSE-MIT and LICENSE-APACHE files for the
// specific language governing permissions and limitations under
// each license.
//! FFI Helper Macros
//!
//! This module provides a set of macros for building safe,
//! ergonomic C FFI bindings. The macros handle common FFI patterns like:
//! - Null pointer checking
//! - C string conversion
//! - Result/error handling with early returns
//! - Option handling for validation
//! - Handle-based object management
//!
//! All macros that perform early returns include `_or_return_` in their names
//! to make control flow explicit and obvious.
//!
//! # 🔍 Test Mode Debugging & Leak Detection
//!
//! The FFI layer includes comprehensive memory tracking and debugging features to catch
//! memory management bugs during development and testing.
//!
//! ## Automatic Leak Detection (All Builds)
//!
//! The pointer registry automatically detects memory leaks at program shutdown. When the
//! registry is dropped, it checks for any pointers that were never freed:
//!
//! ```text
//! ⚠️ WARNING: 3 pointer(s) were not freed at shutdown!
//! This indicates C code did not properly free all allocated pointers.
//! Each pointer should be freed exactly once with cimpl_free().
//! ```
//!
//! **This runs in ALL builds** (debug, release, test) and helps identify:
//! - Forgotten `cimpl_free()` calls in C code
//! - Pointers returned to C that were never cleaned up
//! - Resource leaks that could accumulate over time
//!
//! ## Test-Mode Error Reporting
//!
//! In test builds (`#[cfg(test)]`), additional error reporting is enabled for immediate feedback:
//!
//! ### `cimpl_free` Error Output
//!
//! When `cimpl_free` fails in test mode, it prints detailed diagnostic information to stderr:
//!
//! ```text
//! ⚠️ ERROR: cimpl_free failed for pointer 0x12345678: pointer not tracked
//! This usually means:
//! 1. The pointer was not allocated with box_tracked!/track_box
//! 2. The pointer was already freed (double-free)
//! 3. The pointer is invalid/corrupted
//! ```
//!
//! ## Why These Errors Matter
//!
//! Memory management errors caught by these mechanisms indicate serious bugs:
//! - **Untracked allocations**: Using `Box::into_raw` without `track_box` means `cimpl_free`
//! cannot safely deallocate the memory, causing memory leaks
//! - **Double-free**: Calling `cimpl_free` twice on the same pointer is undefined behavior
//! - **Invalid pointers**: Corrupted or uninitialized pointers will be caught
//! - **Memory leaks**: Pointers never freed waste resources and accumulate over program lifetime
//!
//! ## Production Behavior
//!
//! **In production builds** (without `#[cfg(test)]`):
//! - Leak detection at shutdown still runs (helps catch bugs in integration testing)
//! - `cimpl_free` errors are still returned (as `-1`) and set via [`crate::Error::set_last`]
//! - No stderr output for individual `cimpl_free` failures (quieter for library usage)
//! - C code should always check return values and handle errors appropriately
//!
//! # ⚠️ CRITICAL: Anti-Pattern Detection Guide ⚠️
//!
//! **Before writing ANY FFI code, scan for these patterns and replace:**
//!
//! ```text
//! ❌ if ptr.is_null() { Error::...; return -1; }
//! ✅ deref_mut_or_return_int!(ptr, Type)
//!
//! ❌ match result { Ok(v) => ..., Err(e) => { Error::...; return null } }
//! ✅ ok_or_return_null!(result.map_err(InternalError::from))
//!
//! ❌ unsafe { if ptr.is_null() { ... } &mut *ptr }
//! ✅ deref_mut_or_return_int!(ptr, Type)
//!
//! ❌ unsafe { &*ptr } or unsafe { &mut *ptr }
//! ✅ deref_or_return_int!(ptr, Type) or deref_mut_or_return_int!(ptr, Type)
//!
//! ❌ Manual string length checks and conversion
//! ✅ cstr_or_return!(ptr, -1)
//! ```
//!
//! **Literal strings to search for in your code:**
//! - `if ptr.is_null()` or `if ctx.is_null()` → Use a macro
//! - `match result { Ok` → Use `ok_or_return!`
//! - `unsafe { &*` → Use `deref_or_return!`
//! - `unsafe { &mut *` → Use `deref_mut_or_return!`
//!
//! If you see ANY of these patterns, **STOP and use the appropriate macro below.**
//!
//! # Quick Reference: Which Macro to Use?
//!
//! ## Input Validation (from C)
//! - **Pointer from C**: `deref_or_return_null!(ptr, Type)` → borrows the object as `&Type` for the guard's lifetime
//! - **String from C**: `cstr_or_return_null!(c_str)` → converts C string to Rust `String`
//! - **String array from C**: `cstr_array_or_return_null!(ptr)` → converts NULL-terminated `*const *const c_char` to `Vec<String>`
//! - **Byte array from C**: `bytes_or_return_null!(ptr, len, "name")` → validates & converts to `&[u8]`
//! - **Check not null**: `ptr_or_return_null!(ptr)` → just null check, no deref (for output params)
//!
//! ## Output Creation (to C)
//! - **Box a value**: `box_tracked!(value)` → heap allocate and return pointer
//! - **Return string**: `to_c_string(rust_string)` → convert to C string
//! - **Optional string**: `option_to_c_string!(opt)` → `None` becomes `NULL`
//!
//! ## Error Handling
//! - **External crate Result**: `ok_or_return_null!(result)` → uses From trait automatically
//! - **cimpl::Error Result**: `ok_or_return_null!(result)` → used directly
//!
//! ## Naming Pattern
//! All macros follow: `action_or_return_<what>`
//! - `_null`: Returns `NULL` pointer
//! - `_int`: Returns `-1`
//! - `_zero`: Returns `0`
//! - `_false`: Returns `false`
//!
//! # Type Mapping Guide
//!
//! | Rust Type | C receives | Macro to use | Example |
//! |------------------------|-----------------|-----------------------------------|---------|
//! | `*mut T` (from C) | - | `deref_or_return_null!(ptr, T)`| Getting object from C |
//! | `*const c_char` (from C)| - | `cstr_or_return_null!(s)` | Getting string from C |
//! | `*const c_uchar` + len | - | `bytes_or_return_null!(p, len, "name")` | Getting byte array from C |
//! | `Result<T, ExtErr>` | pointer/int | `ok_or_return_null!(r)` | External crate errors (From trait) |
//! | `Result<T, cimpl::Err>`| pointer/int | `ok_or_return_null!(r)` | Internal validation |
//! | `Option<T>` custom | pointer/int | `some_or_return_null!(o, err)` | Specific error needed |
//! | `T` (owned) | `*mut T` | `box_tracked!(value)` | Returning new object |
//! | `String` | `*mut c_char` | `to_c_string(s)` | Returning string |
//! | `Option<String>` | `*mut c_char` | `option_to_c_string!(opt)` | Optional string |
//!
//! # Common FFI Function Patterns
//!
//! ## Pattern 1: Constructor (returns new object)
//! ```rust,ignore
//! #[no_mangle]
//! pub extern "C" fn thing_new(value: i32) -> *mut Thing {
//! let thing = some_or_return_other_null!(
//! Thing::try_new(value),
//! "Invalid value"
//! );
//! box_tracked!(thing)
//! }
//! ```
//!
//! ## Pattern 2: Parser (external crate Result with centralized mapping)
//! ```rust,ignore
//! // 1. Define error code enum
//! #[repr(i32)]
//! pub enum UuidError {
//! ParseError = 100,
//! }
//!
//! // 2. Implement From trait (centralized mapping!)
//! impl From<uuid::Error> for cimpl::Error {
//! fn from(e: uuid::Error) -> Self {
//! cimpl::Error::new(
//! UuidError::ParseError as i32,
//! format!("ParseError: {}", e)
//! )
//! }
//! }
//!
//! // 3. Use in FFI (automatic conversion via From!)
//! #[no_mangle]
//! pub extern "C" fn uuid_parse(s: *const c_char) -> *mut Uuid {
//! let s_str = cstr_or_return_null!(s);
//! let uuid = ok_or_return_null!(Uuid::from_str(&s_str));
//! box_tracked!(uuid)
//! }
//! ```
//!
//! ## Pattern 3: Method (operates on object)
//! ```rust,ignore
//! #[no_mangle]
//! pub extern "C" fn thing_add(thing: *mut Thing, value: i32) -> i32 {
//! let obj = deref_or_return_int!(thing, Thing);
//! obj.add(value)
//! }
//! ```
//!
//! ## Pattern 4: Method with validation (Option)
//! ```rust,ignore
//! #[no_mangle]
//! pub extern "C" fn date_add_days(date: *mut Date, days: i64) -> *mut Date {
//! let obj = deref_or_return_null!(date, Date);
//! let new_date = some_or_return_other_null!(
//! obj.checked_add_days(days),
//! "Date overflow"
//! );
//! box_tracked!(new_date)
//! }
//! ```
// ============================================================================
// Pointer Management Macros
// ============================================================================
//
// These macros follow a consistent naming pattern:
// - deref_or_return_*: Validate and return reference immediately
// - deref_mut_or_return_*: Same as above, but mutable
//
// All variants support the standard suffixes:
// - _null: Returns NULL on error
// - _neg: Returns -1 on error
// - _zero: Returns 0 on error
// - _false: Returns false on error
// - (base): Custom return value
//
// ----------------------------------------------------------------------------
// Deref Macros - Return reference immediately
// ----------------------------------------------------------------------------
/// Validate pointer and dereference immutably, returning reference
/// Returns early with custom value on error
///
/// # Examples
/// ```rust,ignore
/// let value = deref_or_return!(ptr, Type, -1);
/// ```
/// Validate pointer and dereference immutably, returning reference
/// Returns NULL on error
/// # Examples
/// ```rust,ignore
/// let value = deref_or_return_null!(ptr, Type);
/// ```
/// Validate pointer and dereference immutably, returning reference
/// Returns -1 on error
/// Validate pointer and dereference immutably, returning reference
/// Returns 0 on error
/// Validate pointer and dereference immutably, returning reference
/// Returns false on error
/// Validate pointer and dereference mutably, returning reference
/// Returns early with custom value on error
/// Validate pointer and dereference mutably, returning reference
/// Returns NULL on error
/// Validate pointer and dereference mutably, returning reference
/// Returns -1 on error
/// Resolve a tracked pointer to its real address and dereference it
/// mutably, returning `None` for NULL, untracked, or wrong-type pointers —
/// no error is set, no early return happens.
///
/// This is for internal code (tests, cleanup paths) that decides for itself
/// how to handle a missing value. FFI entry points taking pointers from C
/// should use `deref_mut_or_return!` (NULL is an error) or
/// `deref_mut_option_or_return!` (NULL is a legitimate "not provided")
/// instead, so C gets a proper error for a genuinely bad pointer.
///
/// # Examples
/// ```rust,ignore
/// let stream = deref_mut_option!(ptr, C2paStream).expect("always tracked here");
/// ```
/// Borrow the handle/object for a write operation,
/// return `None` on NULL pointers.
/// NULL in this case is not a showstopper error,
/// since nulls may represent optional parameters.
///
/// # Examples
/// ```rust,ignore
/// if let Some(asset) = deref_mut_option_or_return!(asset_ptr, C2paStream, -1) {
/// asset.do_something();
/// }
/// ```
/// As `deref_mut_option_or_return!`, returning -1.
/// Create a Box-wrapped pointer and track it
/// Returns the raw pointer
/// Create an Arc-wrapped pointer and track it
/// Returns the raw pointer
/// Untrack a pointer from the registry and take ownership of the pointee
/// (ownership transfer from C to Rust), yielding it by value.
///
/// Validates the pointer is tracked with the correct type, removes it from the
/// registry so it can't be double-freed or flagged as a leak, then immediately
/// `Box::from_raw`s it and moves the value out. Because the result is an owned
/// value rather than a pointer, any early return written *after* this macro
/// (e.g. from validating another argument) drops it via Rust's ordinary
/// scope-exit `Drop` — so the input is consumed the same way on every failure
/// path, not just when the rest of the function succeeds.
///
/// # Example
///
/// ```rust,ignore
/// // In c2pa_context_builder_set_signer — signer is moved into the builder:
/// let signer = untrack_or_return_int!(signer_ptr, C2paSigner);
/// builder.set_signer(signer.signer);
///
/// // In c2pa_context_builder_build — builder is consumed to produce a context:
/// let builder = untrack_or_return_null!(builder, C2paContextBuilder);
/// box_tracked!(builder.into_shared())
/// ```
/// Untrack a pointer and take ownership of the pointee, returning -1 on error.
/// Untrack a pointer and take ownership of the pointee, returning NULL on error.
/// Maximum length for C strings when using bounded conversion (1MB)
pub const MAX_CSTRING_LEN: usize = 1048576;
/// Maximum number of entries accepted from a NULL-terminated C string array.
/// Guards against runaway iteration when a caller omits the NULL terminator.
pub const MAX_STRING_ARRAY_LEN: usize = 256;
/// Convert C string with bounded length check or early-return with error value.
/// Errors if the string exceeds MAX_CSTRING_LEN bytes.
/// Convert C string with custom length limit or early-return with error value.
/// Errors if the string exceeds max_len bytes.
/// Handle Result or early-return with error value
///
/// This macro handles Result types using standard Rust From/Into conversion:
/// - External errors are automatically converted via From trait
/// - cimpl::Error is used directly
///
/// # Examples
///
/// ```rust,ignore
/// // External error - automatically converted via From<uuid::Error>
/// let uuid = ok_or_return!(Uuid::from_str(&s), |v| v, std::ptr::null_mut());
///
/// // With cimpl::Error
/// let data = ok_or_return!(some_operation(), |v| v, std::ptr::null_mut());
/// ```
// ============================================================================
// Named Shortcuts (self-documenting for common error values)
// ============================================================================
/// Handle Result, early-return with -1 (negative) on error
///
/// Uses From trait for automatic error conversion.
/// Handle Result, early-return with null on error
///
/// Uses From trait for automatic error conversion.
///
/// # Examples
///
/// ```rust,ignore
/// // Automatically converts external error via From trait
/// let uuid = ok_or_return_null!(Uuid::from_str(&s));
///
/// // Works with cimpl::Error too
/// let data = ok_or_return_null!(validate_something());
/// ```
/// Handle Result, early-return with 0 on error
///
/// Uses From trait for automatic error conversion.
/// Handle Result, early-return with false on error
///
/// Uses From trait for automatic error conversion.
// ============================================================================
// Option Handling Macros
// ============================================================================
//
// These macros convert Option<T> to FFI-friendly error returns.
// Useful for Rust APIs that return Option instead of Result.
/// Handle Option, early-return with custom value if None
///
/// Takes a cimpl::Error to set when the option is None.
///
/// # Examples
///
/// ```rust,ignore
/// // With Error::Other
/// let date = some_or_return!(
/// NaiveDate::from_ymd_opt(2024, 1, 20),
/// Error::Other("Invalid date".to_string()),
/// std::ptr::null_mut()
/// );
///
/// // With different error type
/// let handle = some_or_return!(
/// get_handle(id),
/// Error::InvalidHandle(id),
/// -1
/// );
/// ```
/// Handle Option, early-return with NULL if None
///
/// Takes a cimpl::Error to set when the option is None.
///
/// # Examples
///
/// ```rust,ignore
/// let date = some_or_return_null!(
/// NaiveDate::from_ymd_opt(2024, 1, 20),
/// Error::Other("Invalid date".to_string())
/// );
/// ```
/// Handle Option, early-return with -1 if None
///
/// Takes a cimpl::Error to set when the option is None.
/// Handle Option, early-return with 0 if None
///
/// Takes a cimpl::Error to set when the option is None.
/// Handle Option, early-return with false if None
///
/// Takes a cimpl::Error to set when the option is None.
/// Convenience macro: Handle Option with Error::other message
///
/// Automatically wraps the message string in Error::other().
/// This is the most common case for Option handling in FFI.
///
/// # Examples
///
/// ```rust,ignore
/// let date = some_or_return_other_null!(
/// NaiveDate::from_ymd_opt(2024, 1, 20),
/// "Invalid date"
/// );
/// ```
/// Convenience macro: Handle Option with Error::other message, return -1
/// Convenience macro: Handle Option with Error::other message, return 0
/// Convenience macro: Handle Option with Error::other message, return false
/// Check pointer not null or early-return with error value
/// If the expression is null, set the last error and return null.
/// If the expression is null, set the last error and return -1.
/// Two stream arguments naming the same handle would check it out twice and
/// block until the borrow deadline, then fail with the wrong error. Compare
/// first and fail immediately instead.
/// As `distinct_or_return!`, returning -1.
/// As `distinct_or_return!`, returning null.
/// Gets a buffer to the caller as out-parameter (returns the length).
/// Returns -1 if the bytes could not be allocated.
/// If the expression is null, set the last error and return std::ptr::null_mut().
// Internal routine to convert a *const c_char to a rust String or return a -1 int error.
/// Convert a *const c_char to `Option<String>`.
/// Returns None if the pointer is null.
/// Returns `Some(String)` if the pointer is not null.
/// Returns None if the string is too long.
/// # Examples
/// ```rust,ignore
/// let string = cstr_option!(ptr);
/// ```
/// Converts an `Option<String>` to a C string pointer.
/// Returns `null_mut()` if the Option is None.
///
/// This is commonly used for FFI functions that return optional strings,
/// such as error messages that may or may not be present.
///
/// # Example
/// ```rust,ignore
/// #[no_mangle]
/// pub extern "C" fn get_error_message() -> *mut c_char {
/// option_to_c_string!(Error::last_message())
/// }
/// ```
// ============================================================================
// Byte Array Validation Macros
// ============================================================================
/// Validate and convert raw C byte array to safe slice, returning early on error.
///
/// This macro combines null pointer checking with bounds validation using
/// `safe_slice_from_raw_parts`. It's specifically for byte arrays (`*const c_uchar`)
/// passed from C with an associated length.
///
/// # Examples
///
/// ```rust,ignore
/// #[no_mangle]
/// pub unsafe extern "C" fn process_data(
/// data: *const c_uchar,
/// len: usize
/// ) -> *mut Result {
/// let bytes = bytes_or_return_null!(data, len, "data");
/// // bytes is now a safe &[u8]
/// let result = process(bytes);
/// box_tracked!(result)
/// }
/// ```
/// Validate and convert raw C byte array to safe slice, return NULL on error.
/// Validate and convert raw C byte array to safe slice, return -1 on error.
// ============================================================================
// NULL-Terminated C String Array Macros
// ============================================================================
/// Convert a NULL-terminated C string array (`*const *const c_char`) to a
/// `Vec<String>`, or early-return with a custom error value.
///
/// * A NULL outer pointer is treated as an empty list (not an error).
/// * Returns early if the array exceeds [`MAX_STRING_ARRAY_LEN`] entries
/// (likely a missing NULL terminator).
/// * Returns early if any individual string is not valid UTF-8.
///
/// # Examples
/// ```rust,ignore
/// let refs = cstr_array_or_return!(refs_ptr, std::ptr::null_mut());
/// ```
/// Convert a NULL-terminated C string array to a `Vec<String>`, returning NULL on error.
///
/// See [`cstr_array_or_return`] for full documentation.
/// Convert a NULL-terminated C string array to a `Vec<String>`, returning -1 on error.
///
/// See [`cstr_array_or_return`] for full documentation.
/// Free a pointer that was allocated by cimpl.
///
/// This is a convenience macro wrapper around `cimpl_free` (see [`crate::cimpl_free()`]).
///
/// # Returns
/// - `0` on success
/// - `-1` on error (see [`crate::cimpl_free()`] for details)
///
/// # Error Handling
///
/// On error, the error is set via [`crate::Error::set_last`] and can be retrieved
/// using C2PA error functions. In test mode, errors are also printed to stderr.
///
/// **Best Practice**: Check the return value in production code:
/// ```rust,ignore
/// if cimpl_free!(ptr) != 0 {
/// // Handle error
/// }
/// ```
///
/// # Examples
/// ```rust,ignore
/// let ptr = box_tracked!(MyStruct::new());
/// // ... use ptr ...
/// cimpl_free!(ptr); // Returns 0 on success, -1 on error
/// ```