要在程序开始时加载并在程序结束时卸载 C# DllImport,可以使用以下代码示例:

using System;
using System.Runtime.InteropServices;

public static class DllLoader
{
    private const string DllPath = 'your_dll_path.dll';

    [DllImport(DllPath, CallingConvention = CallingConvention.Cdecl)]
    private static extern void Initialize();

    [DllImport(DllPath, CallingConvention = CallingConvention.Cdecl)]
    private static extern void Cleanup();

    public static void Load()
    {
        Initialize();
        AppDomain.CurrentDomain.ProcessExit += (sender, args) => Cleanup();
        Console.WriteLine('DLL loaded successfully.');
    }
}

public class Program
{
    public static void Main()
    {
        DllLoader.Load();

        // 程序逻辑代码

        Console.WriteLine('Press any key to exit.');
        Console.ReadKey();
    }
}

在上述示例中,DllLoader 类负责加载和卸载 DLL。在 Load 方法中,我们调用 Initialize 函数来加载 DLL。然后,我们使用 AppDomain.CurrentDomain.ProcessExit 事件来订阅程序结束事件,并在事件处理程序中调用 Cleanup 函数来卸载 DLL。这样可以确保在程序结束时正确卸载 DLL。

在 Main 方法中,我们调用 DllLoader.Load 方法来加载 DLL。然后,您可以在程序逻辑代码中执行其他操作。最后,我们等待用户按下任意键退出程序。

请注意,您需要将 DllPath 替换为您实际的 DLL 路径。此外,您还需要根据 DLL 中的函数签名来定义 DllImport 属性。

C# DllImport 加载和卸载:程序启动和结束时管理 DLL

原文地址: https://www.cveoy.top/t/topic/plbG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录