galaxy001
galaxy001

Reputation: 414

Call a method in program from dll in C#

I want to call a method, which is in my program from my dll.
I now I can add an argument public void Bar(Action<string> print, string a). But is there other way to call it?
code in dll:

class Foo {
    public void Bar(string a) {
        //now I want to call method from program
        Program.Print(a); // doesn't work
    }
}

program:

class Program {
    public static void Main(string[] args) {
        var dll = Assembly.LoadFile(@"my dll");
        foreach(Type type in dll.GetExportedTypes())
        {
            dynamic c = Activator.CreateInstance(type);
            c.Bar(@"Hello");
        }
        Console.ReadLine();
    }
    public static void Print(string s) {
        Console.WriteLine(s);
    }
}

from (Loading DLLs at runtime in C#)
Is it possible?

Upvotes: 2

Views: 914

Answers (3)

galaxy001
galaxy001

Reputation: 414

In DLL, I added a reference to program, and that code works now.
code in dll:

class Foo {
    public void Bar(string a) {
        Program.Print(a);
    }
}

program:

class Program {
    public static void Main(string[] args) {
        var dll = Assembly.LoadFile(@"my dll");
        foreach(Type type in dll.GetExportedTypes())
        {
            dynamic c = Activator.CreateInstance(type);
            c.Bar(@"Hello");
        }
        Console.ReadLine();
    }
    public static void Print(string s) {
        Console.WriteLine(s);
    }
}

Upvotes: 0

misticos
misticos

Reputation: 807

You may use reflection for it.

  1. Find type you need to use
  2. Find it's static method you want to call
  3. Invoke the method with an argument

See this website

Upvotes: -1

user12031933
user12031933

Reputation:

You can use a callback.

You add an event in the dll.

From the program you assign the event.

So from the dll, you can call the event.

Put in a public class in the dll:

public event EventHandler MyCallback;

From the program set it to desired method:

MyDllClassInstance.MyCallback = TheMethod;

And now from the dll class you can write:

if (MyCallback != null) MyCallback(sender, e);

You can use any predefined event handler or create your own.

For example for your dll code:

public delegate PrintHandler(string s);

public event PrintHandler MyCallback;

public void Bar(string s)
{
  if (MyCallback != null) MyCallback(s);
}

So in the program you can put:

class Program {
  public static void Main(string[] args) {
      var dll = Assembly.LoadFile(@"my dll");
      foreach(Type type in dll.GetExportedTypes())
      {
          dynamic c = Activator.CreateInstance(type);
          c.MyCallback = Print;
          c.Bar(@"Hello");
      }
      Console.ReadLine();
  }
  public static void Print(string s) {
      Console.WriteLine(s);
  }
}

You can use Action<string> instead of defining a PrintHandler delegate.

Upvotes: 2

Related Questions