Created
October 3, 2020 16:37
-
-
Save Mefistophell/4af0001586541b90e9a344a1b5f00d9a to your computer and use it in GitHub Desktop.
Node.js + Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate libc; | |
use libc::c_char; | |
use std::ffi::CString; | |
use std::ffi::CStr; | |
#[no_mangle] | |
#[allow(clippy::not_unsafe_ptr_arg_deref)] | |
// Concatenates an input string with an existing string literal | |
pub extern "C" fn hello(input: *const c_char) -> *const c_char { | |
let input_cstring: &CStr = unsafe { | |
// Wraps a raw C-string with a safe C string wrapper | |
// Function is unsafe | |
CStr::from_ptr(input) | |
}; | |
// Converts a valid UTF-8 CStr into a string slice | |
let input_str: &str = input_cstring.to_str().unwrap(); | |
// String concatenation | |
let output_string: String = format!("Hello {} from Rust", input_str); | |
// Returns c_char | |
CString::new(output_string).unwrap().into_raw() | |
} | |
#[repr(C)] | |
pub struct Output { | |
result: i64, | |
operands: [i64; 2], | |
description: *const c_char, | |
} | |
impl Output { | |
fn multiplication(operation: Operation) -> Output { | |
let description: String = format!("{} multiplied by {} is {}", operation.operand_a, operation.operand_b, operation.result); | |
Output { | |
result: operation.result, | |
operands: [operation.operand_a, operation.operand_b], | |
description: CString::new(description).unwrap().into_raw(), | |
} | |
} | |
} | |
#[repr(C)] | |
pub struct Operation { | |
operand_a: i64, | |
operand_b: i64, | |
result: i64, | |
} | |
impl Operation { | |
fn multiply(&mut self) { | |
self.result = self.operand_a * self.operand_b; | |
} | |
} | |
#[no_mangle] | |
// Performs multiplication of two numbers and return the [`Output`] struct | |
pub extern fn multiply(mut operation: Operation) -> Output { | |
operation.multiply(); | |
Output::multiplication(operation) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment