Skip to content
เข้าสู่ระบบ

FFI Patterns

Patterns สำหรับ Foreign Function Interface (FFI) ใน Rust ช่วยให้ Rust สามารถ interop กับ C libraries และ expose Rust functions ให้ภาษาอื่นเรียกใช้ได้ เป็นเครื่องมือสำคัญสำหรับ system programming และ integration กับ existing code

การใช้ types ที่ compatible กับ C ABI เป็นพื้นฐานของ FFI ที่ถูกต้อง Rust มี types ใน std::os::raw และ std::ffi สำหรับจุดประสงค์นี้

#[repr(C)] บังคับให้ Rust ใช้ C layout สำหรับ structs และ enums ทำให้ memory layout ตรงกับที่ C compiler สร้าง

use std::os::raw::{c_int, c_char, c_void, c_double};
// repr(C) ensures C-compatible memory layout
#[repr(C)]
struct Point {
x: c_double,
y: c_double,
}
// repr(C) for enums (integer representation)
#[repr(C)]
enum Status {
Ok = 0,
Error = -1,
NotFound = -2,
}
// repr(u32) for specific size
#[repr(u32)]
enum Color {
Red = 0xFF0000,
Green = 0x00FF00,
Blue = 0x0000FF,
}
fn main() {
let point = Point { x: 1.0, y: 2.0 };
println!("Point: ({}, {})", point.x, point.y);
let status = Status::Ok;
println!("Status: {}", status as i32);
let color = Color::Red;
println!("Color: 0x{:06X}", color as u32);
// Size info - important for FFI
println!("\nType Sizes:");
println!(" c_int: {} bytes", std::mem::size_of::<c_int>());
println!(" c_double: {} bytes", std::mem::size_of::<c_double>());
println!(" Point: {} bytes", std::mem::size_of::<Point>());
}

เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม

ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด