Plugins and D programs

Steve Teale steve.teale at britseyeview.com
Thu Mar 13 06:22:54 PDT 2014


One of the primary uses of dynamic loading of libraries might 
well be to provide plugins. By plugins I mean extensions to an 
existing program that can be added to the program at run-time, 
and can be written by separate authors who don't necessarily have 
access to the source code of the program, but who do understand 
the rules provided by the program documentation as to what 
capabilities the plugin must have.

The most obvious way to allow a D program to cope with plugins, 
is to specify an interface to which the plugin is expected to 
conform. Communication between the program and the plugin, after 
the latter is loaded would then be restricted to calls provided 
by that interface.

One further library method would likely be necessary to allow for 
the acquisition of an instance of the plugin, and its attachment 
to the program.

So, we could have

module ifd;
interface I
{
    string saySomething();
}

The plugin could then be:

module plugin;
import ifd;
import std.stdio;

class Plugin: I
{
    this() { writeln("plugin ctor"); }

    string saySomething() { return "I am plugin"; }
}

I getInstance()
{
    return new Plugin();
}

And our program could be:

module main;
import core.runtime;
import std.stdio;
import ifd;

extern(C) void* dlsym(void*, const char*);
extern(C) void* dlopen(const char*, int);

alias I function() pfi;

I getPlugin(string name)
{
    // Take your pick from these two - makes no odds
    //void* lib = dlopen("plugin.so\0".ptr, 1);
    void* lib = Runtime.loadLibrary(name~".so");

    if (lib is null)
    {
       writeln("failed to load plugin shared object");
       return null;
    }

    void* vp = dlsym(lib, "_D6plugin11getInstanceFZC3ifd1I\0".ptr);
    if (vp is null)
    {
       writeln("plugin creator function not found");
       return null;
    }
    pfi f = cast(pfi) vp;
    I x = f();
	if (x is null)
	{
		writeln("creation of plugin failed");
		return null;
	}
	return x;
}

void main()
{
    I x = getPlugin("plugin");
    writeln(x.saySomething());
}

Unfortunately, the result of running the program is:

steve at steve-desktop:~/scratch/piif$ ./main
plugin ctor

Segmentation fault (core dumped)

Which suggests that the library was loaded, the symbol found, and 
an instance of plugin created.

The two pieces were built using dmd2.064 with:

main : ifd.d main.d
	dmd -c ifd.d
	dmd -c main.d
	dmd main.o ifd.o -L-ldl -defaultlib=libphobos2.so -L-rpath=.

plugin : plugin.d
	dmd -c -shared -fPIC plugin.d
	dmd plugin.o -shared -defaultlib=libphobos2.so -map

clean :
	rm *.o
	rm main
	rm plugin.so

Does anyone have any suggestions as to what might be going wrong 
here? I have further examples, but I guess I should do them one 
at a time.

Steve


More information about the Digitalmars-d mailing list