LINUX C# 加载本地库的范例代码

网上搜索了一下,有人提供了办法,测试通过:

public partial class MainWindow : Gtk.Window
{
    public MainWindow() : base(Gtk.WindowType.Toplevel)
    {
        Build();
    }
 
    protected void OnDeleteEvent(object sender, DeleteEventArgs a)
    {
        Application.Quit();
        a.RetVal = true;
    }
 
    const string NATIVE_PATH = "./libtioplugininterface.so";
    const string NATIVE_INIT = "init";
 
 
    [DllImport("libdl.so")]
    protected static extern IntPtr dlopen(string filename, int flags);
 
    [DllImport("libdl.so")]
    protected static extern IntPtr dlsym(IntPtr handle, string symbol);
 
    [DllImport("libdl.so")]
    protected static extern IntPtr dlclose(IntPtr handle);
 
    const int RTLD_NOW = 2; // for dlopen's flags
 
    private delegate int native_init(int param);
 
    static bool NativeInit()
    {
        IntPtr hModule = dlopen(NATIVE_PATH, RTLD_NOW);
        if (hModule.Equals(IntPtr.Zero))
        {
            Console.WriteLine("LoadLibrary fail=" + NATIVE_PATH);
            return false;
        }
        Console.WriteLine("dlopen() OK");
 
        IntPtr address = dlsym(hModule, NATIVE_INIT);
        if (address == IntPtr.Zero)
        {
            Console.WriteLine("GetProcAddress fail=" + NATIVE_INIT);
            return false;
        }
        Console.WriteLine("dlsym() OK");
 
        Delegate proc = Marshal.GetDelegateForFunctionPointer(address, typeof(native_init));
        int result = ((native_init)proc)(0);
        Console.WriteLine("native_init() OK");
 
        dlclose(hModule);
        return true;
    }
 
 
    protected void OnButton2Pressed(object sender, EventArgs e)
    {
        this.button2.Visible = false;
        NativeInit();
    }
}
上一篇:1、深入理解计算机系统 笔记,系统综述


下一篇:低代码的自动化工作流靠谱嘛?对企业有何帮助?