core.stdc.stdlib._compare_fp_t and qsort

H. S. Teoh hsteoh at quickfur.ath.cx
Mon Mar 12 01:51:32 UTC 2018


On Mon, Mar 12, 2018 at 01:04:06AM +0000, Joe via Digitalmars-d-learn wrote:
> On Sunday, 11 March 2018 at 23:26:04 UTC, Stefan Koch wrote:
> > You have to pass a pointer to the function.
> > Otherwise it'll be a parenthsis-less call.
> > use :  qsort(recs, num_recs, (Record *).sizeof, &compar);
> 
> After passing a pointer, getting some other error messages, I changed
> the call to
> 
>     qsort(cast(void *)recs, num_recs, cast(size_t)(Record *).sizeof,
> &compar);
> 
> and the latest error is:
> 
> Error: function core.stdc.stdlib.qsort (scope void* base, ulong nmemb, ulong
> size, extern (C) int function(scope const(void*), scope const(void*))
> @system compar) is not callable using argument types (void*, ulong, ulong,
> int function(const(void*) p1, const(void*) p2))
> 
> I fail to see which argument is causing the problem now.
[...]

I wonder if the problem is because qsort expects a C linkage function
(`extern (C) int function(...)`), but you're passing a D linkage (i.e.,
native) function to it.  You can't do that, because the order of
arguments in a D linkage function may differ from a C linkage function,
and could potentially cause a subtle bug if you're not expecting the
arguments in a different order. (I actually ran into this myself, in a
different context where there was no type enforcement like there is
here, and it took me a long time to track down the problem.)

If indeed this is the problem, try adding `extern (C)` to your D
function to make it compatible with C linkage, and that should do the
trick.  I think.


T

-- 
If you look at a thing nine hundred and ninety-nine times, you are perfectly safe; if you look at it the thousandth time, you are in frightful danger of seeing it for the first time. -- G. K. Chesterton


More information about the Digitalmars-d-learn mailing list