1

I want to use library function using dlopen and dlsym, library function has a default argument. When I use this function using dynamic loading of library it works fine, so how can I achieve that.?

extern "C" int checklib(char *arg1, char *arg2 = NULL)
{

        if(arg2 != NULL)
        {
                printf("arg2 is not null");
        }


        printf("arg1 = %s\n", arg1);
        
}       

int main()
{
        void *libHandle = NULL;
        char *error;
        int ret;

        libHandle = dlopen("libtest.so", RTLD_LAZY);

        if (!libHandle)
        {
                fprintf(stderr, "%s\n", dlerror());
                return(-8);
        }

        typedef int (*fun_ptr_to_test)(char *);

        fun_ptr_to_test test;

        test = (fun_ptr_to_test) dlsym(libHandle, "checklib");

        if ((error = dlerror()) != NULL)
        {
                fprintf(stderr, "%s\n", error);
                if (libHandle)
                                dlclose(libHandle);
                return(-8);
        }
        ret = test("dadfsj");
        if (libHandle)
        dlclose(libHandle);
        return ret;
}


I am getting some garbage value in arg2. so how can i achieve it.

karel
  • 5,489
  • 46
  • 45
  • 50
vikas_saini
  • 159
  • 1
  • 10
  • Actually, there is no such thing as 'default argument', it's just an illusion created by the compiler. Do specify every argument when you call the function. – Lorinczy Zsigmond Apr 26 '19 at 08:59
  • Default arguments are aspects of a function **declaration**, not the function itself—which is what you get a pointer to. Calling the function with a different function type is simply undefined behavior. – Davis Herring Apr 26 '19 at 22:43
  • 4
    Per “panta rei” (sorry, Paste is broken): possible duplicate of [Call function with default argument from .dll with c++](https://stackoverflow.com/questions/49692473/call-function-with-default-argument-from-dll-with-c) – Davis Herring Apr 26 '19 at 22:44

0 Answers0