Skip to content

Commit 2501e5f

Browse files
committed
rust: add static/shared library linking example
1 parent d02624c commit 2501e5f

File tree

1 file changed

+63
-3
lines changed

1 file changed

+63
-3
lines changed

runtime/rust/src/main.rs

Lines changed: 63 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,16 +24,61 @@ mod bar {
2424
/// This struct is not [Bar]
2525
pub struct Foo1;
2626

27-
fn main() {
28-
println!("Hello, world!");
27+
//
28+
// external static C library example
29+
//
30+
use std::ffi::c_void;
31+
32+
#[link(name = "uuid", kind = "static")] // note: for shared lib, remove `kind = "static"`
33+
unsafe extern "C" {
34+
// typedef unsigned char uuid_t[16]; // &[u128] or &[u8; 16]
35+
fn uuid_generate_time(out: *mut u8) -> c_void;
36+
fn uuid_generate_random(out: *mut u8) -> c_void;
37+
}
38+
39+
fn example_external_C_static_lib() {
40+
println!("\n\n+++ example_external_C_static_lib()");
41+
// let uuid = 0u128;
42+
let mut uuid = [0u8; 16]; // array of 16 unsigned byte zeroes
43+
unsafe { uuid_generate_time(uuid.as_mut_ptr()) };
44+
print_uuid(&uuid);
45+
unsafe { uuid_generate_random(uuid.as_mut_ptr()) };
46+
print_uuid(&uuid);
47+
}
48+
49+
// print as xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
50+
fn print_uuid(uuid: &[u8; 16]) {
51+
print!("UUID: ");
52+
for i in 0..uuid.len() {
53+
print!("{:02x}", uuid[i]);
54+
match i {
55+
3 | 5 | 7 | 9 => print!("-"),
56+
_ => ()
57+
}
58+
}
59+
println!("");
60+
}
61+
62+
//
63+
// Example usage of the regex crate
64+
//
65+
fn example_crate_usage() {
66+
println!("\n\n+++ example_crate_usage()");
2967

30-
// Example usage of the regex crate
3168
let re = Regex::new(r"^Hello, (.+)!$").unwrap();
3269
let text = "Hello, world!";
3370
if let Some(caps) = re.captures(text) {
3471
println!("Greeting target: {}", &caps[1]);
3572
}
3673

74+
}
75+
76+
//
77+
// websockets client example
78+
//
79+
fn example_websocket_client() {
80+
println!("\n\n+++ example_websocket_client()");
81+
3782
let (mut socket, response) =
3883
connect("ws://corefx-net-http11.azurewebsites.net/WebSocket/EchoWebSocket.ashx")
3984
.expect("Can't connect");
@@ -54,6 +99,21 @@ fn main() {
5499
let _ = socket.close(None);
55100
}
56101

102+
103+
fn main() {
104+
println!("Hello, world!");
105+
106+
example_external_C_static_lib();
107+
108+
example_crate_usage();
109+
110+
example_websocket_client();
111+
112+
}
113+
114+
//
115+
// tests
116+
//
57117
#[cfg(test)]
58118
mod tests {
59119
use super::*;

0 commit comments

Comments
 (0)