io_lifetimes/
example_ffi.rs

1//! This is just a sample of what FFI using this crate can look like.
2
3#![allow(missing_docs)]
4
5#[cfg(any(unix, target_os = "wasi", target_os = "hermit"))]
6use crate::{BorrowedFd, OwnedFd};
7#[cfg(windows)]
8use crate::{BorrowedHandle, HandleOrInvalid};
9
10#[cfg(any(unix, target_os = "wasi", target_os = "hermit"))]
11use libc::{c_char, c_int, c_void, size_t, ssize_t};
12#[cfg(windows)]
13use {
14    core::ffi::c_void,
15    windows_sys::core::PCWSTR,
16    windows_sys::Win32::Foundation::BOOL,
17    windows_sys::Win32::Security::SECURITY_ATTRIBUTES,
18    windows_sys::Win32::Storage::FileSystem::{
19        FILE_CREATION_DISPOSITION, FILE_FLAGS_AND_ATTRIBUTES, FILE_SHARE_MODE,
20    },
21    windows_sys::Win32::System::IO::OVERLAPPED,
22};
23
24// Declare a few FFI functions ourselves, to show off the FFI ergonomics.
25#[cfg(any(unix, target_os = "wasi", target_os = "hermit"))]
26extern "C" {
27    pub fn open(pathname: *const c_char, flags: c_int, ...) -> Option<OwnedFd>;
28}
29#[cfg(any(unix, target_os = "wasi"))]
30extern "C" {
31    pub fn read(fd: BorrowedFd<'_>, ptr: *mut c_void, size: size_t) -> ssize_t;
32    pub fn write(fd: BorrowedFd<'_>, ptr: *const c_void, size: size_t) -> ssize_t;
33}
34#[cfg(any(unix, target_os = "wasi"))]
35pub use libc::{O_CLOEXEC, O_CREAT, O_RDONLY, O_RDWR, O_TRUNC, O_WRONLY};
36
37// The Windows analogs of the above. Note the use of [`HandleOrInvalid`] as
38// the return type for `CreateFileW`, since that function is defined to return
39// [`INVALID_HANDLE_VALUE`] on error instead of null.
40#[cfg(windows)]
41extern "system" {
42    pub fn CreateFileW(
43        lpfilename: PCWSTR,
44        dwdesiredaccess: u32,
45        dwsharemode: FILE_SHARE_MODE,
46        lpsecurityattributes: *const SECURITY_ATTRIBUTES,
47        dwcreationdisposition: FILE_CREATION_DISPOSITION,
48        dwflagsandattributes: FILE_FLAGS_AND_ATTRIBUTES,
49        htemplatefile: HANDLE,
50    ) -> HandleOrInvalid;
51    pub fn ReadFile(
52        hfile: BorrowedHandle<'_>,
53        lpbuffer: *mut c_void,
54        nnumberofbytestoread: u32,
55        lpnumberofbytesread: *mut u32,
56        lpoverlapped: *mut OVERLAPPED,
57    ) -> BOOL;
58    pub fn WriteFile(
59        hfile: BorrowedHandle<'_>,
60        lpbuffer: *const c_void,
61        nnumberofbytestowrite: u32,
62        lpnumberofbyteswritten: *mut u32,
63        lpoverlapped: *mut OVERLAPPED,
64    ) -> BOOL;
65}
66
67#[cfg(windows)]
68pub use {
69    windows_sys::Win32::Foundation::HANDLE,
70    windows_sys::Win32::Storage::FileSystem::{
71        CREATE_ALWAYS, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, FILE_GENERIC_READ, FILE_GENERIC_WRITE,
72        OPEN_EXISTING,
73    },
74};