Safe FFI Wrapper
๋ฌ์คํธ๋ _์ธ๋ถ ๊ธฐ๋ฅ ํธ์ถ(FFI)_์ ์ง์ํฉ๋๋ค.
์ด๋ฅผ ์ด์ฉํ์ฌ C์์ ์ฌ์ฉํ ํด๋ ๋ด ํ์ผ์ด๋ฆ์ ์ฝ์ด์ค๋ glibc
ํจ์๋ฅผ ๋ง๋ค ๊ฒ์
๋๋ค.
์๋ ๋ฆฌ๋ ์ค ๋ฉ๋ด์ผ ๋ฌธ์๋ค์ ์ฐธ์กฐํ์๊ธฐ ๋ฐ๋๋๋ค:
์๋ ์ฝ๋๋ฅผ https://play.rust-lang.org/์ ๋ณต์ฌํ๊ณ ๋น ์ง ํจ์์ ๋ฉ์๋๋ฅผ ์ฑ์๋ด ๋๋ค.
Rust has great support for calling functions through a foreign function interface (FFI). We will use this to build a safe wrapper the
glibc
functions you would use from C to read the filenames of a directory.You will want to consult the manual pages:
You will also want to browse the
std::ffi
module, particular forCStr
andCString
types which are used to hold NUL-terminated strings coming from C. The Nomicon also has a very useful chapter about FFI.Copy the code below to https://play.rust-lang.org/ and fill in the missing functions and methods:
// TODO: remove this when you're done with your implementation. #![allow(unused_imports, unused_variables, dead_code)] mod ffi { use std::os::raw::{c_char, c_int, c_long, c_ulong, c_ushort}; // Opaque type. See https://doc.rust-lang.org/nomicon/ffi.html. #[repr(C)] pub struct DIR { _data: [u8; 0], _marker: core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>, } // Layout as per readdir(3) and definitions in /usr/include/x86_64-linux-gnu. #[repr(C)] pub struct dirent { pub d_ino: c_long, pub d_off: c_ulong, pub d_reclen: c_ushort, pub d_type: c_char, pub d_name: [c_char; 256], } extern "C" { pub fn opendir(s: *const c_char) -> *mut DIR; pub fn readdir(s: *mut DIR) -> *const dirent; pub fn closedir(s: *mut DIR) -> c_int; } } use std::ffi::{CStr, CString, OsStr, OsString}; use std::os::unix::ffi::OsStrExt; #[derive(Debug)] struct DirectoryIterator { path: CString, dir: *mut ffi::DIR, } impl DirectoryIterator { fn new(path: &str) -> Result<DirectoryIterator, String> { // Call opendir and return a Ok value if that worked, // otherwise return Err with a message. unimplemented!() } } impl Iterator for DirectoryIterator { type Item = OsString; fn next(&mut self) -> Option<OsString> { // Keep calling readdir until we get a NULL pointer back. unimplemented!() } } impl Drop for DirectoryIterator { fn drop(&mut self) { // Call closedir as needed. unimplemented!() } } fn main() -> Result<(), String> { let iter = DirectoryIterator::new(".")?; println!("files: {:#?}", iter.collect::<Vec<_>>()); Ok(()) }
์ญ์ฃผ
- DirectoryIterator, Iterator, Drop impl ๋ธ๋ก์ ์ฑ์ฐ๋ฉด ๋ฉ๋๋ค.
- ์ฐธ์กฐ๋ฌธ์๋ฅผ ์น ํ์ด๋ ์ด๋ ค์ด๋ฐ(โฆ)