Search code examples
c++ccharconstantsdlsym

Passing const char* to function from external library that takes a char*


Consider I have the following function in a dynamic external library libExternal.dylib:

void print(char* str)
{
    // Changes the first char to 'a' and prints the string
    *str = 'a';
    printf("%s\n", str);
}

Next, I have an executable that loads this external library and calls the function (error checking omitted):

int main(int argc, const char * argv[])
{
    void* hLib = dlopen("libExternal.dylib", RTLD_LAZY | RTLD_LOCAL);

    typedef void(*printFunc)(const char*);
    printFunc func = (printFunc)dlsym(hLib, "print");

    std::string test = "hello";
    func(test.c_str());

    dlclose(hLib);

    return 0;
}

As you can see, the function defined in the library takes a char* as parameter. When using dlsym, I made it get a function that takes a const char*. And it works!

My question is, how is this possible? The dynamic loader ignores const types? I really couldn't find an answer anywhere, so please help me! :)

EDIT: I know this code is wrong, I'm just trying to understand how is this possible.


Solution

  • It works but it doesn't mean it's correct.

    It doesn't ignore const types, you're casting the external function to a function which accepts const types:

    typedef void(*printFunc)(const char*);
                             ^^^^^^^^^^^
    
    printFunc func = (printFunc)dlsym(hLib, "print");
                     ^^^^^^^^^^^
    

    And try to use right function signature to avoid undefined behavior due to modifying a const value.