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