Using dlopen/dlsym

Jacob Carlborg via Digitalmars-d digitalmars-d at puremagic.com
Tue Dec 27 06:56:48 PST 2016


On 2016-12-27 01:05, Andrei Alexandrescu wrote:
> Consider this code:
>
> ===========
> import core.sys.posix.dlfcn;
> extern(C) void fun() {}
> void main()
> {
>     fun();
>     void *hndl = dlopen(null, RTLD_LAZY);
>     if (!hndl) assert(0);
>     auto p = dlsym(hndl, "fun".ptr);
>     if (!p)
>     {
>         import core.stdc.stdio;
>         printf("%s\n", dlerror());
>     }
> }
> ===========
>
> It works (i.e. outputs nothing) on http://dpaste.dzfl.pl and on
> Vladimir's machine.
>
> On my Mint and Ubuntu machines it outputs:
>
> ./test: undefined symbol: fun
>
> I'm building with no flags using dmd. What could be the problem here?

Although I don't think this is the problem, the correct way to check if 
dlsym was successful is to call dlerror, not check if the result from 
dlsym was null. From the man page:

"Since the value of the symbol could actually be NULL (so that a NULL 
return from dlsym() need not indicate an error), the correct way to test 
for an error is to call dlerror(3) to clear any old error conditions, 
then call dlsym(), and then call dlerror(3) again, saving its return 
value into a variable, and check whether this saved value is not NULL"

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list