getch 是一个在 C 语言编程中常用的函数,用于从键盘读取一个字符,但不回显到屏幕上。

在 Windows 环境下,getch 实现通常包含在 <conio.h> 头文件中。需要注意的是,getch 这个符号并非标准,标准的符号是 _getch,虽然 getch 一般会被指向 _getch,但你应当使用 _getch 而非 getch

在 Unix/Linux 环境下,没有系统提供的 getch 实现,我们可以通过以下方法实现:

#include <termio.h>

int getch(void) {
struct termios tm, tm_old;
int fd = 0, ch; if (tcgetattr(fd, &tm) < 0) { // 保存现在的终端设置
return -1;
} tm_old = tm;
cfmakeraw(&tm); // 更改终端为原始模式,该模式下所有的输入数据以字节处理
if (tcsetattr(fd, TCSANOW, &tm) < 0) { // 设置上更改之后的设置
return -1;
} ch = getchar();
if (tcsetattr(fd, TCSANOW, &tm_old) < 0) { // 更改设置为最初的样子
return -1;
} return ch;
}

其中 struct termiostcgetattrtcsetattrcfmakeraw 以及 getchar 的定义为:

typedef unsigned char	cc_t;
typedef unsigned int speed_t;
typedef unsigned int tcflag_t;
#define NCCS 32
struct termios{
tcflag_t c_iflag; /* input mode flags */
tcflag_t c_oflag; /* output mode flags */
tcflag_t c_cflag; /* control mode flags */
tcflag_t c_lflag; /* local mode flags */
cc_t c_line; /* line discipline */
cc_t c_cc[NCCS]; /* control characters */
speed_t c_ispeed; /* input speed */
speed_t c_ospeed; /* output speed */
}; int tcgetattr(int __fd, struct termios *__termios_p);
void cfmakeraw(struct termios *__termios_p);
int tcsetattr(int __fd, int __optional_actions, const struct termios *__termios_p);
int getchar(void);

据此,我们可以通过 Rust 的 FFI 为 rust 实现一个 getch

#[cfg(target_os = "windows")]
mod conio {
use std::os::raw::c_int; extern "C" {
pub fn _getch() -> c_int;
}
} #[cfg(target_os = "linux")]
#[allow(non_camel_case_types)]
mod conio {
use std::os::raw::c_int;
type tcflag_t = ::std::os::raw::c_uint;
type speed_t = ::std::os::raw::c_uint;
type cc_t = ::std::os::raw::c_uchar; const NCCS: usize = 32;
const TCSANOW: i32 = 0; #[repr(C)]
#[derive(Default, Copy, Clone)]
struct termios {
c_iflag: tcflag_t,
c_oflag: tcflag_t,
c_cflag: tcflag_t,
c_lflag: tcflag_t,
c_line: cc_t,
c_cc: [cc_t; NCCS],
c_ispeed: speed_t,
c_ospeed: speed_t,
} extern "C" {
fn tcgetattr(__fd: c_int, __termios_p: *mut termios) -> c_int;
fn tcsetattr(__fd: c_int, __optional_actions: c_int, __termios_p: *const termios) -> c_int;
fn cfmakeraw(__termios_p: *mut termios);
fn getchar() -> c_int;
} #[allow(unused_mut, unused_assignments)]
pub fn _getch() -> c_int {
unsafe {
let mut tm: termios = Default::default();
let mut tm_old: termios = Default::default();
let fd = 0;
let mut ch: c_int;
if tcgetattr(fd, &mut tm) < 0 {
return -1;
} tm_old = tm;
cfmakeraw(&mut tm);
if tcsetattr(fd, TCSANOW, &mut tm) < 0 {
return -1;
} ch = getchar();
if tcsetattr(fd, TCSANOW, &mut tm_old) < 0 {
return -1;
} ch
}
}
} #[allow(unused_unsafe)]
fn getch() -> char {
unsafe { conio::_getch() as u8 as char }
}

C/C++ 以及 Rust 中的 getch() 实现的更多相关文章

  1. Rust 中的继承与代码复用

    在学习Rust过程中突然想到怎么实现继承,特别是用于代码复用的继承,于是在网上查了查,发现不是那么简单的. C++的继承 首先看看c++中是如何做的. 例如要做一个场景结点的Node类和一个Sprit ...

  2. Rust 中的类型转换

    1. as 运算符 as 运算符有点像 C 中的强制类型转换,区别在于,它只能用于原始类型(i32 .i64 .f32 . f64 . u8 . u32 . char 等类型),并且它是安全的. 例 ...

  3. Rust中的RefCell和内部可变性

    RefCell Rust在编译阶段会进行严格的借用规则检查,规则如下: 在任意给定时间,要么只能有一个可变引用,要么只能有多个不可变引用. 引用必须总是有效. 即在编译阶段,当有一个不可变值时,不能可 ...

  4. Rust中的Slices

    这个slice切片,python中有,go中有, 但确实,Rust中最严格. 精彩见如下URL: Rust 程序设计语言(第二版) 简体中文版 · GitBook (Legacy) https://k ...

  5. 刷完欧拉计划中难度系数为5%的所有63道题,我学会了Rust中的哪些知识点?

    我为什么学Rust? 2019年6月18日,Facebook发布了数字货币Libra的技术白皮书,我也第一时间体验了一下它的智能合约编程语言MOVE,发现这个MOVE是用Rust编写的,看来想准确理解 ...

  6. 【译】Rust中的array、vector和slice

    原文链接:https://hashrust.com/blog/arrays-vectors-and-slices-in-rust/ 原文标题:Arrays, vectors and slices in ...

  7. 【译】理解Rust中的闭包

    原文标题:Understanding Closures in Rust 原文链接:https://medium.com/swlh/understanding-closures-in-rust-21f2 ...

  8. 【译】理解Rust中的局部移动

    原文标题:Understanding Partial Moves in Rust 原文链接:https://whileydave.com/2020/11/30/understanding-partia ...

  9. 【译】理解Rust中的Futures (一)

    原文标题:Understanding Futures In Rust -- Part 1 原文链接:https://www.viget.com/articles/understanding-futur ...

  10. 【译】理解Rust中的Futures(二)

    原文标题:Understanding Futures in Rust -- Part 2 原文链接:https://www.viget.com/articles/understanding-futur ...

随机推荐

  1. Python prometheus_client使用方式

    #!/usr/bin/env python # -*- coding: utf8 -*- import socket,re from prometheus_client import generate ...

  2. Docker之基础(一)

    接触Docker有很久一段时间, 但是没有好好总结一下, 借此公司项目全面容器化, 记录一下常用的Docker操作 概况: 本次容器化的项目包括PHP+Python项目,PHP是基于php-fpm的基 ...

  3. linux之Zip

    安装: apt-get) apt-get install zip yum) yum install -y unzip zip 语法: zip [选项] 压缩包名 源文件或源目录列表 注意,zip 压缩 ...

  4. .Net知识技能大全

    .Net知识技能大全 更多请见https://www.dotnetshare.com C#常见运算符 一元运算符(+.-.!.~.++.--) 算术运算符(*./.%.+. – ) 移位运算符(< ...

  5. css var实现网页换肤

    前情 最近在做需求开发,要求根据后台传来的配置对网页换肤,按以往的换肤思路应该是写好几套样式做切换达到换肤效果,但是现在想做到能根据后台配置动态修改. 原理 通过css3新增变量特性,把颜色定义为变量 ...

  6. P11378[GESP202412 七级]燃烧 题解

    闲话 花了一个小时. 主要原因:条初始值硬控我半小时,题目看错硬控我半小时(悲). 正文 看题目,就是求从哪个点出发所得到的所有单调下降序列的总长度最长(这个描述好奇怪,不过意思是对的). 题目中说的 ...

  7. ThreeJs-07操控物体实现家具编辑器

    本章节实现效果,通过gui快速添加场景,家具,并且可以快速设置家具实现一个编辑器效果 一.基础设置与物体添加列表 用之前做过的一个案例来改 首先不要这个模型,然后换个背景颜色,并且添加一个网格辅助器 ...

  8. WinDbg: Failed to find runtime module (coreclr.dll or clr.dll or libcoreclr.so)

    当我们通过 WinDbg 启动一个 .NET 的程序时,WinDbg 将会在运行可执行之前执行一个中断,此时还没有加载 .NET 的运行时. 但是,SOS 扩展需要 clr.dll 或者 corecl ...

  9. GraphQL Part VIII: 使用一对多查询

    今天,我们引入两个新的实体来处理客户与订单.客户与订单之间是一对多的关系,一个客户可以拥有一个或者多个订单,反过来,一个订单只能被某个客户所拥有. 可以按照 Engity Framework 的约定配 ...

  10. PostgreSQL 的历史

    title: PostgreSQL 的历史 date: 2024/12/23 updated: 2024/12/23 author: cmdragon excerpt: PostgreSQL 是一款功 ...