如何在Rust中使用libc :: mount替换nix :: mount :: mount

问题描述

我想在Rust FFI中使用'nix'库替换为'libc'。

我想使用nix :: mount :: mount()替换为libc :: mount()。现在我有了以下代码

libc::mount(ptr::null(),path.as_ptr(),ptr::null(),libc:: MS_SLAVE,ptr::null())

我只想知道如何替换nix库中的ptr :: null(),我尝试使用“无”来做,但是失败了。请帮助我,谢谢。

显示错误

39 |     nix::mount::mount(
   |     ^^^^^^^^^^^^^^^^^ cannot infer type for type parameter `P1` declared on the function `mount`
   | 
  ::: /root/.cargo/registry/src/mirrors.ustc.edu.cn-15f9db60536bad60/nix-0.19.0/src/mount.rs:57:27
   |
57 | pub fn mount<P1: ?Sized + NixPath,P2: ?Sized + NixPath,P3: ?Sized + NixPath,P4: ?Sized + NixPath>(
   |                           ------- required by this bound in `nix::mount::mount`
   |
   = note: cannot satisfy `_: nix::NixPath`

解决方法

nix::mount::mount具有功能签名:

pub fn mount<P1: ?Sized + NixPath,P2: ?Sized + NixPath,P3: ?Sized + NixPath,P4: ?Sized + NixPath>(
    source: Option<&P1>,target: &P2,fstype: Option<&P3>,flags: MsFlags,data: Option<&P4>
) -> Result<()>

如您所见,参数sourcefstypedata采用通用类型parameter的选项。如果传入Some(value),则可以根据value的类型来推断这些类型参数,但是如果传入None,则编译器没有足够的信息来推断类型这些参数。

您可以将参数的类型明确指定为实现NixPath的某种类型,例如Path

nix::mount::mount<Path,Path,Path>(None,path,None,MsFlags::MS_SLAVE,None)

或者您可以直接在None上指定类型参数:

nix::mount::mount(None::<Path>,None::<Path>,None::<Path>)