1 Callbacks allow C function pointers to invoke ucode closures. The `qsort` function 2 demonstrates callback usage with integer and string array sorting. 3 4 -- Testcase -- 5 {% 6 import * as ffi from 'ffi'; 7 8 // Method 1: Predeclare with cdef(), then wrap bare name 9 ffi.cdef(` 10 void qsort(void *base, size_t nmemb, size_t size, 11 int (*compar)(const void *, const void *)); 12 int strcmp(const char *, const char *); 13 `); 14 15 let narr = ffi.ctype('int[5]', [56, 4, 12, 1, 5]); 16 let qsort_fn = ffi.C.wrap('qsort'); 17 18 qsort_fn(narr.ptr(), narr.length(), narr.itemsize(), 19 (a, b) => a.deref('int') - b.deref('int')); 20 21 print("sorted: "); 22 for (let i = 0; i < 5; i++) { 23 print(narr.get(i), " "); 24 } 25 print("\n"); 26 -- End -- 27 28 -- Expect stdout -- 29 sorted: 1 4 5 12 56 30 -- End -- 31 32 33 String array sorting using strcmp callback. 34 35 -- Testcase -- 36 {% 37 import * as ffi from 'ffi'; 38 39 // Method 2: No cdef(), use full declaration in wrap() 40 let sarr = ffi.ctype('const char *[3]', ['foo', 'bar', 'qrx']); 41 let qsort_fn = ffi.C.wrap('void qsort(void *, size_t, size_t, int (*)(const void *, const void *))'); 42 let strcmp = ffi.C.wrap('int strcmp(const char *, const char *)'); 43 44 qsort_fn(sarr.ptr(), sarr.length(), sarr.itemsize(), 45 (a, b) => strcmp(a.deref('const char *'), b.deref('const char *'))); 46 47 print("sorted: "); 48 for (let i = 0; i < 3; i++) { 49 print(sarr.get(i), " "); 50 } 51 print("\n"); 52 -- End -- 53 54 -- Expect stdout -- 55 sorted: bar foo qrx 56 -- End -- 57
This page was automatically generated by LXR 0.3.1. • OpenWrt