c#从嵌入的资源dll文件加载程序集并导出函数

本文介绍了如何使用C#从嵌入的资源DLL文件加载程序集,并导出函数供Excel VBA调用。通过.NET的AssemblyResolve事件和DllImport,实现了在Excel中生成二维码的功能。详细步骤包括DLL的生成、IL代码的处理,以及VBA调用C#函数的方法。此外,还讨论了数据类型的匹配和依赖性问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过AssemblyResolve event实现。然后就可以using直接调用了。

GetManifestResourceStream里面加载的资源名称字符串由"项目名.路径文件夹名.dll文件名带扩展名"构成。看资源文件路径就可以得到。

static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {//=> Assembly.LoadFrom($@"{new FileInfo(args.RequestingAssembly.Location).DirectoryName}\{args.Name.Split(',')[0]}.dll");
            using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Qrcode.Resources.QRCoder.dll"))
            { //从嵌入的资源dll文件加载程序集
                byte[] byData = new byte[stream.Length];
                stream.Read(byData, 0, byData.Length);
                return Assembly.Load(byData);
            }
        }

 下面是一个我写的导出c#类给excel vba调用的代码。目的是在excel里生成二维码。我只生成X64的dll因为我的office是64位的应用。

using QRCoder;
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Reflection;
using System.IO;

namespace Qrcodes
{
    [ComVisible(true), ClassInterface(ClassInterfaceType.AutoDual)]
    public class myqrcode
    {
        public void CreateIm([MarshalAs(UnmanagedType.BStr)]string s, [MarshalAs(UnmanagedType.BStr)]string filePath)
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值