0
点赞
收藏
分享

微信扫一扫

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

双井暮色 2022-01-27 阅读 59


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

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();
}
}



举报

相关推荐

0 条评论