简体   繁体   English

从DLL获取程序汇编

[英]Get Assembly of program from a DLL

I would like to access a function of a program from which is attached a DLL. 我想访问附有DLL的程序的功能。

In DLL I've tried: 在DLL中,我尝试过:

Assembly assembly = Assembly.GetExecutingAssembly();
Type type = assembly.GetType("Uranium");
MethodInfo methodInfo = type.GetMethod("Util");

methodInfo.Invoke("SendClient", new object[] { Packet.GetData()});

But not works I get a null exception but not say the line. 但不起作用,我得到一个空异常,但不说这一行。 The running program is called and namespace is 'Uranium', the class is 'Util' and function is 'SendClient'. 调用运行中的程序,名称空间为“ Uranium”,类为“ Util”,函数为“ SendClient”。

I have been able solve it on my own. 我已经能够自行解决。

Code: 码:

Assembly assembly = Assembly.LoadFrom("Uranium.exe");
Type type = assembly.GetType("Uranium.Util");
MethodInfo methodInfo = type.GetMethod("SendClient");

methodInfo.Invoke(null, new object[] { Packet.GetData() });

You first need to find the assembly that contains the type. 您首先需要找到包含类型的程序集。 Also, you need to pass the class name to GetType() , not the namespace, and method name to GetMethod() , not class name. 另外,您需要将类名称传递给GetType()而不是名称空间,并将方法名称传递给GetMethod()而不是类名称。

foreach (Assembly currentassembly in AppDomain.CurrentDomain.GetAssemblies()) 
{
    Type t = currentassembly.GetType("Util", false, true);
    if (t != null) 
    {
        MethodInfo methodInfo = type.GetMethod("SendClient");
        methodInfo.Invoke(Activator.CreateInstance(t),new object[] { Packet.GetData()});
    }
}

From what I can read from the code you've posted you try to invoke the function Util of class Uranium. 从您所发布的代码中我所看到的,您尝试调用类Uranium的函数Util。 And you're passing a string as the instance of the class. 并且您要传递一个字符串作为类的实例。

This should be more like what you're trying to do: 这应该更像您要执行的操作:

Assembly assembly = Assembly.GetExecutingAssembly();
Type type = assembly.GetType("Util");
MethodInfo methodInfo = type.GetMethod("SendClient");

methodInfo.Invoke(Activator.CreateInstance(type), new object[] { Packet.GetData()});

If SendClient is a static member function then Activator.CreateInstance(type) can be replaced with null . 如果SendClient是静态成员函数,则Activator.CreateInstance(type)可以替换为null And of course you should add checks that the GetType and GetMethod return values are not null 当然,您应该添加检查以确保GetTypeGetMethod返回值不为null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM