gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:02:46 24 4
gpt4 key购买 nike

所以我有这个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com