c# - 如何从资源中的 DLL 调用函数?

标签 c# dll .net-assembly messagebox loader

所以我有这个 DLL 和另一个我认为被称为注入(inject)器/加载器的东西?它基本上将我的 DLL 加载到它自己的进程中,因此它将我的 DLL 加载到“Injector.exe”的进程中 在下面的示例中,它不是从资源而是从桌面加载它,这里同样适用。

现在它正在加载,它实际上并没有调用任何函数,这就是我的问题所在。

我想在加载 DLL 时调用一些 Messagebox 函数。

据我所知,最合乎逻辑的方法是在 btnAssemblyLoad_Click 事件中执行此操作,因此当事件发生时,它会调用 DLL 中的函数。 问题是我不知道这会叫什么,我读了一些关于“反射”的东西,但我不确定这是我需要的。

我应该如何处理这件事?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AssemblyLoader
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if(ofd.ShowDialog() == DialogResult.OK)
            {
                tbAssemblyLocation.Text = ofd.FileName;
            }
        }

        private void btnAssemblyLoad_Click(object sender, EventArgs e)
        {

            AssemblyName an = AssemblyName.GetAssemblyName(tbAssemblyLocation.Text);
            Assembly.Load(an);
        }
    }
}

动态链接库

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MSgBOxDllCS
{
    public class Funcs
    {
        public void CallMessageBox()
        {
            MessageBox.Show("Hello");

        }
    }
}

最佳答案

您需要调用非静态类的实例方法,见下文。

// Step 1: load assembly to memory
var an = AssemblyName.GetAssemblyName(tbAssemblyLocation.Text);
var assembly = Assembly.Load(an);

// Step 2: get type from the assembly by name
var type = assembly.GetType("MSgBOxDllCS.Funcs");

// Step 3: get method of the type
var method = type.GetMethod("CallMessageBox");

// Step 4: create instance of the type
var funcs = Activator.CreateInstance(type);

// Step 5: invoke the instance method
method.Invoke(funcs, null);

一般来说,您正在构建的称为插件框架,互联网上有大量示例说明如何完成,您也可以根据您的要求利用现有框架。

关于c# - 如何从资源中的 DLL 调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43657952/

相关文章:

.net - 如何使用 Reflexil v1.5 修改 .net 属性?

c# - 创建简单的 c++.net 包装器。一步步

c++ - 从 C++ 调用 VB DLL

c++ - 我可以跨 DLL 边界传递 FILE 对象吗?

.net - .NET 核心程序集中非常特殊的 PublicKey

c# 程序集, friend 程序集

c# - 使用 XamlReader 创建的 DataTemplate 无法找到 StaticResources

c# - 使用 Dapper.Net 进行调试不会进入 Dapper 调用 - 未找到 SqlMapper.cs

c# - 卸载应用程序域时出错。 (来自 HRESULT : 0x80131015) occurs when closing a form 的异常

C# - 如何将 DLL 嵌入到项目中?