03.04 Rust 编程视频教程(进阶)——025

视频地址

头条地址:https://www.ixigua.com/i6775861706447913485

源码地址

github地址:见扩展链接。

讲解内容

(1)调用方式。不安全函数和方法与常规函数方法十分类似,除了其开头有一个额外的 unsafe。例子1:

<code>unsafe fn dangerous() {
println!("Do some dangerous thing");
}
fn main() {
unsafe {
dangerous();
}
println!("Hello, world!");
}/<code>

(2)创建不安全代码的安全抽象

<code>fn foo() {
let mut num = 5;
let r1 = &num as *const i32;
let r2 = &mut num as *mut i32;
unsafe {
println!("r1 is: {}", *r1);
println!("r2 is: {}", *r2);
}
}
fn main() {
foo();
}/<code>

(3)使用extern函数调用外部代码extern关键字,有助于创建和使用 外部函数接口(Foreign Function Interface, FFI)。例子1:调用c语言函数

<code>extern "C" {
fn abs(input: i32) -> i32;
}

fn main() {
unsafe {
println!("abs(-3): {}", abs(-3));
}
}/<code>

例子2:c语言调用rust语言(a)cargo new foo –lib(b)vim src/lib.rs编写代码:

<code>#![crate_type = "staticlib"]
#[no_mangle]
pub extern fn foo(){
println!("use rust");
}/<code>

编写cargo.toml

<code>[lib]
name = "foo"
crate-type = ["staticlib"]/<code>

(c)编译后生成 libfoo.a的静态库(d)编写c语言的代码:

<code>//main.c
#include <stdint.h>
#include <stdio.h>
extern void foo();
int main() {
foo();
return 0;
}/<stdio.h>/<stdint.h>/<code>

(e)编译运行:gcc -o main main.c libfoo.a -lpthread -ldl


分享到:


相關文章: