Sign in to follow this  
methinks

Problem with dynamic objects using dlsym

Recommended Posts

I'm trying to learn how to write plugins (OSX Yosemite).

Everything compiles and runs properly, the shared object is loaded, but function in the shared object doesn't execute.

 

All the files remain in the same directory.

 

The host application, compiled as follows:

g++ -ldl -o Host Host.cpp

// Host.cpp
 
#include <iostream>

#include <dlfcn.h>



using namespace std;



int main(int argc, char* argv[])

{

    void * plugin = dlopen("Plugin.mod", RTLD_NOW);



    if(plugin == nullptr)

    {

        cout << "Error opening file" << endl;

    }

    else

    {

        cout << "File open, attempting to access function" << endl;

        dlerror();

        dlsym(plugin, "run"); // This is where the line "Plugin Running" should be printed to the console

        char * errMsg = dlerror();

        if(errMsg)

        {

            cout << "Unable to access function" << endl;

        }

        else

        {

            cout << "Success: " << endl;

        }

        dlclose(plugin);

    }

}

The plugin that gets called

g++ -fPIC -c Plugin.cpp

g++ -shared -o Plugin.mod Plugin.o

// Plugin.cpp
#include <iostream>



using namespace std;



extern "C" void run()

{

    cout << "Plugin running" << endl;

}

and the output:

File open, attempting to access function
Success:

 

Is this a problem with the code, or the compilation?

Share this post


Link to post
Share on other sites

I think it's because you need to export the function.

On Windows :

__declspec( dllexport )

On other platform :

__attribute__ ( ( __visibility__ ( "default" ) ) )

EDIT:  On this case you normally have a compile error.

Edited by Alundra

Share this post


Link to post
Share on other sites

You can also use this way (more c++, T is the type of the function of course) :

typedef T* (*PtrFunc)();
PtrFunc RunFunction = reinterpret_cast<PtrFunc>(dlsym(plugin, "run"));
Edited by Alundra

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this