C++动态库封装C#库,验证动态库环境

windows 平台、VS2019、x64

当C++编译的动态库提供给C#的开发人员时,需要实现一个C#的库使用委托去调用C++动态库。

当C#开发人员链接使用C#的动态库时,如果没有完全拷贝C++动态库所依赖的其他动态库时,就会出现运行报错。

但是报错时,不会提示缺少了什么库,这里在C#的中增加一个函数,去检测环境下缺少了什么动态库,便于排查问题。

实现

public class DynamicLibraryDetector
{
    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    private static extern uint GetDllDirectory(uint nBufferLength, System.Text.StringBuilder lpBuffer);

    private static readonly List<string> RequiredDlls = new List<string>
    {
        "yourLibrary1.dll",
        "yourLibrary2.dll",
        "yourLibrary3.dll",
        // 添加所有依赖的 DLL 名称
    };

    /// <summary>
    /// Checks the existence of all required DLLs in the current working directory, DLL directory, and PATH environment variable.
    /// Throws a DllNotFoundException if any required DLL is missing.
    /// </summary>
    /// <exception cref="DllNotFoundException">
    /// Thrown if one or more required DLLs are not found.
    /// </exception>
    public static void Check()
    {
        List<string> missingDlls = new List<string>();
        List<string> foundDlls = new List<string>();

        // 获取当前 DLL 目录
        string currentDllDirectory = GetCurrentDllDirectory();

        foreach (var dll in RequiredDlls)
        {
            // 检查当前工作目录
            if (File.Exists(dll))
            {
                foundDlls.Add(dll);
                continue;
            }

            // 检查当前 DLL 目录
            string fullPathInCurrentDir = Path.Combine(currentDllDirectory, dll);
            if (File.Exists(fullPathInCurrentDir))
            {
                foundDlls.Add(dll);
                continue;
            }

            // 检查 PATH 环境变量中的所有路径
            string[] paths = Environment.GetEnvironmentVariable("PATH").Split(';');
            bool foundInPath = false;

            foreach (var path in paths)
            {
                string fullPath = Path.Combine(path, dll);
                if (File.Exists(fullPath))
                {
                    foundInPath = true;
                    foundDlls.Add(dll);
                    break;
                }
            }

            if (!foundInPath)
            {
                missingDlls.Add(dll);
            }
        }

        if (missingDlls.Count > 0)
        {
            throw new DllNotFoundException($"Missing DLL files: {string.Join(", ", missingDlls)}. Please make sure to copy them to the application directory or set the correct path in PATH. ");
        }
    }

    private static string GetCurrentDllDirectory()
    {
        const int bufferSize = 1024;
        var buffer = new System.Text.StringBuilder(bufferSize);
        GetDllDirectory((uint)bufferSize, buffer);
        return buffer.ToString();
    }
}

使用

DynamicLibraryDetector.Check();
posted @ 2024-11-13 10:04  Yzi321  阅读(81)  评论(0)    收藏  举报