Thread: Loading a .dll

  1. #1
    mustang benny bennyandthejets's Avatar
    Join Date
    Jul 2002
    Posts
    1,401

    Loading a .dll

    I want to implement a simple plugin system for my program. Each plugin will have a couple interface functions, ie for initialization and execution, which can have defined signatures, using primitive types. These functions would have identical signatures in every .dll.

    How can I load multiple .dlls, but still be able to call the specific function I need?
    [email protected]
    Microsoft Visual Studio .NET 2003 Enterprise Architect
    Windows XP Pro

    Code Tags
    Programming FAQ
    Tutorials

  2. #2
    Banned nickname_changed's Avatar
    Join Date
    Feb 2003
    Location
    Australia
    Posts
    986
    OK, this is how I do it:

    I check all files in a directory for .DLL or .EXE's. Then, I try to load each DLL. Then, I look at every Type in each DLL to see what it is. If it implements IPlugin (an interface I created that all my plugins or extensions follow), I load the object.

    Code:
    // here you could loop through a directory and try every file...
    Assembly[] assemblies = new Assembly[1];
    try
    {
    	assemblies[0] = Assembly.LoadFrom(@"C:\firstPlugin.dll");
    }
    catch { }
    try
    {
    	assemblies[1] = Assembly.LoadFrom(@"C:\secondPlugin.dll");
    }
    catch { }
    
    // search each loaded assembly for the type
    foreach (Assembly assembly in assemblies)
    {
    	foreach (Type type in assembly.GetTypes())
    	{
    		if (type.IsClass)
    		{
    			// try to create an intance of it - maybe not the 
    			// safest method but works
    			try
    			{
    			    object o = Activator.CreateInstance(type);
    
    			    // IPlugin is a custom interface we made
    				if (o is IPlugin)
    				{
    				    IPlugin plugin = (IPlugin)o;
    				    plugin.Execute();
    				}
    			}
    			catch
    			{
    				
    			}
    		}
    	}
    }

  3. #3
    mustang benny bennyandthejets's Avatar
    Join Date
    Jul 2002
    Posts
    1,401
    Thanks, that looks perfect.
    [email protected]
    Microsoft Visual Studio .NET 2003 Enterprise Architect
    Windows XP Pro

    Code Tags
    Programming FAQ
    Tutorials

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Cargo loading system
    By kyle rull in forum C Programming
    Replies: 1
    Last Post: 04-20-2009, 12:16 PM
  2. loading .h, .dll, and .lib
    By sigh in forum Windows Programming
    Replies: 4
    Last Post: 02-08-2008, 01:32 AM
  3. added start menu crashes game
    By avgprogamerjoe in forum Game Programming
    Replies: 6
    Last Post: 08-29-2007, 01:30 PM
  4. Problem with a .dll file
    By GaPe in forum Windows Programming
    Replies: 2
    Last Post: 10-29-2003, 01:20 PM
  5. Loading Screen
    By pinkcheese in forum Windows Programming
    Replies: 2
    Last Post: 04-06-2002, 11:48 PM