C# Newbie Question: Dynamically Calling a DLL

G

Guest

I have created a simple DLL that contains this code:

using System;
namespace Test2
{
public class Test
{
int intAmount = 100;
public int GetValue()
{
return intAmount;
}
}
}

When I want to dynamically reference this DLL and return its value, how do I
accomplish this?

I was doing this:

string sDLLName = "C:\\Test\\Test2.dll";
Assembly objAssembly = System.Reflection.Assembly.LoadFrom(sDLLName);
MethodInfo Method = objAssembly.GetTypes()[0].GetMethod("GetValue");

This code seems to function fine to this point, but any attempts to try to
"invoke" or retrieve the value from the DLL fail miserably. (I am leaving all
of that code out; it is all green anyway :) It may be something simple, but I
am missing the "zen" of this completely. Any help would be appreciated. Once
I have the method, what is my next step?

Thanks!
Mo
 
M

Mattias Sjögren

This code seems to function fine to this point, but any attempts to try to
"invoke" or retrieve the value from the DLL fail miserably.

Failing how, exactly?

Since it's an instance method you need an instance of Test to call it
on. I don't see you creating that anywhere.



Mattias
 
J

Joshua Flanagan

I'm not sure what you've already tried, but something along these lines
should work:

string sAssemblyName="Test2";
// string sDLLName = @"c:\Test\" + sAssemblyName + ".dll";
// You should always use Assemly.Load (specifying the assembly name)
// if you are trying to use the functionality provided in the assembly.
// You generally should only use Assembly.LoadFrom if you are making a
// a utility that analyzes the contents of the assembly.
Assembly assembly = Assembly.Load(sAssemblyName);
object testObject = assembly.CreateInstance("Test2.Test");
MethodInfo method = testObject.GetType().GetMethod("GetValue");
object result = method.Invoke(testObject, new object[0]);


As a nitpicky aside - try to break the habit of using using the "obj"
pseudo-hungarian prefix on your variables. If you need to keep using
"str" for your strings, fine, but "obj" makes absolutely no sense.
EVERY variable in .NET is an object. Do you really want to prepend
"obj" to every variable?

Hope this helps.

Joshua Flanagan
http://flimflan.com/blog
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top