程式語言 - Rust - SDL v1.2 - Hello, world!



參考資訊:
https://www.rust-lang.org/learn/get-started
https://users.rust-lang.org/t/calling-c-function-with-string/41448/10
http://bzz.wallizard.com:8081/share/books/RUST/Programming%20Rust%202nd%20Edition.pdf

main.rs

use std::ffi::CString;
use std::os::raw::{c_char, c_int, c_uchar, c_void};

#[repr(C)]
struct SDL_Surface {
    _private: [u8; 0],
}

#[link(name = "SDL")]
unsafe extern "C" {
    fn SDL_Init(flags: u32) -> c_int;

    fn SDL_SetVideoMode(
        width: c_int,
        height: c_int,
        bpp: c_int,
        flags: u32,
    ) -> *mut SDL_Surface;

    fn SDL_Flip(screen: *mut SDL_Surface) -> c_int;

    fn SDL_Delay(ms: u32);

    fn SDL_Quit();
}

#[link(name = "SDL_gfx")]
unsafe extern "C" {
    fn stringRGBA(
        dst: *mut SDL_Surface,
        x: i16,
        y: i16,
        text: *const c_char,
        r: c_uchar,
        g: c_uchar,
        b: c_uchar,
        a: c_uchar,
    ) -> c_int;
}

const SDL_INIT_VIDEO: u32 = 0x00000020;
const SDL_HWSURFACE: u32 = 0x00000001;

fn main() {
    unsafe {
        SDL_Init(SDL_INIT_VIDEO);
        let screen = SDL_SetVideoMode(
            320,
            240,
            16,
            SDL_HWSURFACE,
        );

        let msg = CString::new("Hello, world!").unwrap();
        stringRGBA(
            screen,
            100,
            100,
            msg.as_ptr(),
            0xff,
            0xff,
            0xff,
            0xff,
        );

        SDL_Flip(screen);
        SDL_Delay(3000);
        SDL_Quit();
    }
}

Cargo.toml

[package]
name = "rust-sdl12"
version = "0.1.0"
edition = "2021"

[[bin]]
name = "main"
path = "main.rs"

[dependencies]
sdl = "0.3.6"

編譯、執行

$ cargo build
$ cargo run