Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load a .DLL file and access methods from class within?

Tags:

c#

dll

I'm completely new to loading in libraries like this, but here's where I stand:

I have a homemade DLL file it's about as simple as it gets, the class itself and a method. In the home program that loads this library, I have:

Assembly testDLL = Assembly.LoadFile("C:\\dll\\test.dll");

From here, I'm kind of stuck. As far as I know, it's loading it correctly because it gives me errors when I change the name.

What do I do from here? How exactly do I load the class & methods within it?

Thanks.

like image 804
scrot Avatar asked Jul 06 '09 16:07

scrot


3 Answers

Use Assembly.GetTypes() to get a collection of all the types, or Assembly.GetType(name) to get a particular type.

You can then create an instance of the type with a parameterless constructor using Activator.CreateInstance(type) or get the constructors using Type.GetConstructors and invoke them to create instances.

Likewise you can get methods with Type.GetMethods() etc.

Basically, once you've got a type there are loads of things you can do - look at the member list for more information. If you get stuck trying to perform a particular task (generics can be tricky) just ask a specific question an I'm sure we'll be able to help.

like image 94
Jon Skeet Avatar answered Nov 03 '22 01:11

Jon Skeet


This is how you can get the classes if you know the type.

Assembly assembly = Assembly.LoadFrom("C:\\dll\\test.dll");

// Load the object
string fullTypeName = "MyNamespace.YourType";

YourType myType = assembly.CreateInstance(fullTypeName);

The full type name is important. Since you aren't adding the .dll you can't do a Using because it is not in your project.

If you want all I would just Jon Skeet answer.

like image 27
David Basarab Avatar answered Nov 03 '22 01:11

David Basarab


If you want to dynamically load an assembly, and then invoke methods from classes therein, you need to perform some form of dynamic invoke.

Check here for basic advice on that.

The only bit missing is how to get the type itself, which can easily be retrieved wth code like this:

foreach (Type t in assemblyToScan.GetTypes())
        {
            if(condition)
                //do stuff
        }

And if you simply want to use the assembly statically (by having the assembly available at compile time), then the answer fom Launcy here on this page is the way to go.

like image 3
Kenan E. K. Avatar answered Nov 03 '22 00:11

Kenan E. K.