How to implement qsort_r

Eric Blake
Thu Dec 4 22:06:00 GMT 2014

On 12/04/2014 11:13 AM, Eric Blake wrote:
> BSD was at least consistent in having 'opaque, callback' turn into
> 'callback(opaque, ...)' (opaque always first), but as Corinna points
> out, this form is not shim-able, while glibc's opaque-last is.

Or, you CAN shim it, but the shim costs an extra invocation of an
indirect function call, and thus can become noticeably slower in
benchmarks.  Given BSD semantics,

static int compar_shim(void *func, const void *a, const void *b)
  int (*compar)(const void *, const void *) = func;
  return compar(a, b);
void qsort(void *base, size_t nel, size_t width,
           int (*compar)(const void *, const void *))
  qsort_r(base, nel, width, compar, compar_shim);

would work, but it calls both 'compar_shim(compar, a, b)' and 'compar(a,
b)' for every comparison, while the glibc shim calls merely 'compar(a,
b, NULL)' and compar() just ignores the 3rd parameter.

Eric Blake   eblake redhat com    +1-919-301-3266
Libvirt virtualization library

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 539 bytes
Desc: OpenPGP digital signature
URL: <>

More information about the Newlib mailing list