Search code examples
c++castingshared-librariesvoid-pointersdlsym

I can call a function imported with dlsym() with a wrong signature, why?


host.cpp has:

int main (void)
{
    void * th = dlopen("./p1.so", RTLD_LAZY);
    void * fu = dlsym(th, "fu");

    ((void(*)(int, const char*)) fu)(2, "rofl");

    return 0;
}

And p1.cpp has:

#include <iostream>

extern "C" bool fu (float * lol)
{
    std::cout << "fuuuuuuuu!!!\n";
    return true;
}

(I intentionally left errors checks out)

When executing host, “fuuuuuuuu!!!” is printed correctly, even though I typecasted the void pointer to the symbol with a completely different function signature.

Why did this happen and is this behavior consistent between different compilers?


Solution

  • Because there's no information about function signature in void pointer. Or any information besides the address. You might get in trouble if you started to use parameters, tho.