1#!/bin/bash
2
3source ctypes.sh
4
5declare -i sortsize=128     # size of array
6declare -a values           # array of values
7set -e
8
9# int compare(const void *, const void *)
10function compare {
11    local -a x=(int)
12    local -a y=(int)
13    local -a result
14
15    # extract the parameters
16    unpack $2 x
17    unpack $3 y
18
19    # remove the prefix
20    x=${x##*:}
21    y=${y##*:}
22
23    # calculate result
24    result=(int:$((x - y)))
25
26    # return result to caller
27    pack $1 result
28
29    return
30}
31
32# Generate a function pointer to compare that can be called from native code.
33callback -n compare compare int pointer pointer
34
35# Generate an array of random values
36for ((i = 0; i < sortsize; i++)); do
37    values+=(int:$RANDOM)
38done
39
40# Allocate space for integers
41dlcall -n buffer -r pointer malloc $((sortsize * 4))
42
43# Pack our random array into that native array
44pack $buffer values
45
46# Now qsort can sort them
47dlcall qsort $buffer long:$sortsize long:4 $compare
48
49# Unpack the sorted array back into a bash array
50unpack $buffer values
51
52# Verify they're sorted
53if ! sort --check --numeric <(IFS=$'\n'; echo "${values[*]##*:}"); then
54    echo FAIL
55    exit 1
56fi
57
58echo PASS
59