tra*_*ber 2 c# linux .net-core
我正在致力于将 .Net Core 3.1 应用程序从 Windows 移植到 Linux。我在 Windows 上有一个 ourdevice.dll,以及为 Linux 构建的等效 ourdevice.so。该 dll 是我们在 Windows 上使用 pinvoke 包装器使用的本机 dll。
我们使用 kernel32.dll 中的 DllImports 从本机 dll 加载函数
[DllImport("kernel32.dll", EntryPoint = "LoadLibrary", SetLastError = true)]
public static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32.dll")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
[DllImport("kernel32.dll")]
public static extern bool FreeLibrary(IntPtr hModule);
Run Code Online (Sandbox Code Playgroud)
我们为每个要导入的函数创建委托:
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate short AdcOpen([MarshalAs(UnmanagedType.LPStr)] string adcName, [MarshalAs(UnmanagedType.LPStr)] string protocol, [MarshalAs(UnmanagedType.LPStr)] string port, ref short handle, byte performSwReset);
private AdcOpen adcOpen;
Run Code Online (Sandbox Code Playgroud)
然后我们映射所有本机函数,如下所示:
IntPtr pAddressOfFunction;
pDll = LoadLibrary(LibraryName);
// check if library is loaded
if (pDll != IntPtr.Zero)
{
// get proc address of the native functions
pAddressOfFunction = GetProcAddress(pDll, "AdcOpen");
if (pAddressOfFunction != IntPtr.Zero)
adcOpen = (AdcOpen)Marshal.GetDelegateForFunctionPointer(pAddressOfFunction, typeof(AdcOpen));
else
message += "Function AdcOpen not found\n";
//snip loading all the exported functions
}
Run Code Online (Sandbox Code Playgroud)
在Linux应用程序中,显然我们不能使用kernel32.dll。我们正在 Linux 上的 .Net core 中编写 C#,并且我们有本机模块 ourdevice.so。如何将函数从本机 Linux 模块导入到我们的 C# 包装器中?有可能吗?
加载库:
[DllImport("libdl", ExactSpelling = true)]
public static extern IntPtr dlopen(string filename, int flags);
Run Code Online (Sandbox Code Playgroud)
获取过程地址:
[DllImport("libdl", ExactSpelling = true)]
public static extern IntPtr dlsym(IntPtr handle, string symbol);
Run Code Online (Sandbox Code Playgroud)
免费图书馆:
[DllImport("libdl", ExactSpelling = true)]
public static extern int dlclose(IntPtr handle);
Run Code Online (Sandbox Code Playgroud)
使用示例:
const int RTLD_NOW = 0x002;
IntPtr pDll = dlopen("ourdevice.so.0", RTLD_NOW);
IntPtr pAddressOfFunction = dlsym(pDll, "AdcOpen");
...
dlclose(pDll);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1958 次 |
| 最近记录: |