How to get a class from another process?

Parker Shiung 1 Reputation point
2023-01-05T06:48:29.207+00:00

I have two processes in my computer.
One is a dll file which creates a class and gets some data from it when a particular application executes.
The other one is an exe file that uses this data and executes some methods.

How to pass the class of the dll file to the exe file and use it?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,231 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Jack J Jun 24,286 Reputation points Microsoft Vendor
    2023-01-05T08:45:11.997+00:00

    @Parker Shiung , Welcome to Microsoft Q&A, there are two methods for you to pass the class of the dll file to the exe file and use it.

    I create a class library and a console app.

    Dll:

    namespace TestDll  
    {  
        public class Student  
        {  
            public int Id { get; set; }  
      
            public string Name { get; set; }  
      
            public void SayHello (string name,int id)  
            {  
                string result = string.Format("My Name is {0} and Id is {1}", name, id);  
                Console.WriteLine(result);  
            }  
                  
      
        }  
    }  
    

    A. You could add the dll file as the reference for the console app, then you could use the following code to use the class directly:

    using TestDll;  
      
    namespace ConsoleApp1  
    {  
        internal class Program  
        {  
            static void Main(string[] args)  
            {  
                Student stu=new Student();  
                stu.Name = "test1";  
                stu.Id = 1001;  
                stu.SayHello(stu.Name, stu.Id);  
            }  
        }  
    }  
    

    B. You could use reflection to call the method, like the following code:

    var DLL = Assembly.LoadFile(@"TestDll.dll");  
            var theType = DLL.GetType("TestDll.Student");  
            var c = Activator.CreateInstance(theType);  
            PropertyInfo name = theType.GetProperty("Name");  
            name.SetValue(c, "test1");  
            PropertyInfo id = theType.GetProperty("Id");  
            id.SetValue(c, 1001);  
            var method = theType.GetMethod("SayHello");  
            method.Invoke(c, new object[] { name.GetValue(c),id.GetValue(c) });  
    

    Hope my solution could help you.

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.