vb6 上 运行 .net 2.0 dll 中的问题

Issue in running .net 2.0 dll on vb6

VB6 项目中的 Net framework 2.0 dll。 .Net Framework 4.5 中的相同代码(命名空间是 PasswordHashLibrary 而不是 PasswordHashLibrary2.0)在 vb6 项目上运行良好,但这次我遗漏了一些东西。

这是我在 .net v2.0 上的 C# 代码

//using statements here

namespace PasswordHashLibrary2._0
{
public interface ComClassInterface
{
}

public class Hash : ComClassInterface
{

    private const int PBKDF2IterCount = 1000; // default for Rfc2898DeriveBytes
    private const int PBKDF2SubkeyLength = 256 / 8; // 256 bits
    private const int SaltSize = 128 / 8; // 128 bits

    //[ComVisible(true)]
    public string HashPassword(string password)
    {
        if (password == null)
        {
            throw new ArgumentNullException("password cannot be null");
        }

        // Produce a version 0 (see comment above) text hash.
        byte[] salt;
        byte[] subkey;
        var deriveBytes = new Rfc2898DeriveBytes(password, SaltSize, PBKDF2IterCount);
            salt = deriveBytes.Salt;
            subkey = deriveBytes.GetBytes(PBKDF2SubkeyLength);


        var outputBytes = new byte[1 + SaltSize + PBKDF2SubkeyLength];
        Buffer.BlockCopy(salt, 0, outputBytes, 1, SaltSize);
        Buffer.BlockCopy(subkey, 0, outputBytes, 1 + SaltSize, PBKDF2SubkeyLength);
        return Convert.ToBase64String(outputBytes);
    }



    // some other functions
}

}

在项目属性中选中 "Register for COM Interop"。 在 assemblyInfo.cs

[assembly: ComVisible(true)]

之后我用 regasm 注册了这个 dll

现在在 vb6 项目上,此 .tlb 可作为 PasswordHashLibrary2_0 使用,我将其添加为参考。我的Vb6项目代码如下

Private Sub Form_Load()

Dim objHash As New PasswordHashLibrary2_0.Hash
Dim temp As String

temp = objHash.HashPassword("fsfds")

End Sub

当我运行这个程序时,objHash没有设置,你可以看到

在我向前移动之后,这条线 vb6 给我错误

Run-time error '-2147024894 (80070002)':

Automation error The system cannot find the file specified

您可以使用 gacutil 在 GAC(全局程序集缓存)中注册它以确保 CLR 能够识别它:

gacutil /l PasswordHashLibrary2_0.dll

之后,在regasm注册.NET DLL程序集时尝试使用codebase参数开关:

regasm [directory_path]\PasswordHashLibrary2_0.dll /codebase /tlb:[directory_path]\PasswordHashLibrary2_0.tlb

通常 CLR 在指向存储 VB 项目的同一目录之前在 GAC 中查找程序集名称,检查已存储在 GAC 中的 DLL 和 TLB 文件是否与执行这些步骤后的 DLL 位于同一位置.

嘿嘿,我发现问题了!

首先因为@Tetsuya 指出了 gacutil,所以我为 gacutil 添加了强名称,然后尝试安装程序集,但出现错误

Failure adding assembly to cache the module was expected to contain an assembly manifest.

这意味着程序集已损坏,因此我将程序集名称更改为 PasswordHashLibrary2.dll 并重建项目。

然后注册这个程序集并添加引用。最后不知何故,在测试 New 关键字时,已从 vb6 代码中删除,因此我开始收到错误

Run-time error 91 object variable or block variable not set

如此修复它,现在它可以工作了:)

干杯