Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add example for parallel sort #15

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ edition = "2021"
readme = "README.md"
repository = "https://github.com/STEllAR-GROUP/hpx-rs"
description = """
Bindings to hpx for interoperating with stellar-group hpx library for
Bindings to hpx for interoperating with stellar-group hpx library for
concurrency and parallelism.
"""
categories = ["api-bindings"]
Expand All @@ -17,4 +17,4 @@ publish = false
hpx-sys = { path = "hpx-sys", version = "0.1.0" }

[workspace]
members = []
members = [ "hpx-examples"]
7 changes: 7 additions & 0 deletions hpx-examples/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[package]
name = "hpx-examples"
version = "0.1.0"
edition = "2021"

[dependencies]
hpx-sys = { path = "../hpx-sys", version = "0.1.0" }
19 changes: 19 additions & 0 deletions hpx-examples/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#![feature(vec_into_raw_parts)]
#![feature(random)]
use core::array::from_fn;
use std::{env, process, random};

fn hpx_main(_: Vec<String>) -> i32 {
let numbers: &[i32; 16384] = &from_fn(|_| random::random::<i32>());
let list: &mut Vec<i32> = &mut Vec::<i32>::from(numbers);
println!("{:#?}", list);
// Sort the array in parallel.
hpx_sys::ffi::hpx_sort_comp(list, |a, b| a < b);
println!("{:#?}", list);
hpx_sys::ffi::finalize();
return 0;
}
fn main() {
let args = env::args().collect::<Vec<String>>();
process::exit(hpx_sys::init(hpx_main, args));
}
39 changes: 38 additions & 1 deletion hpx-sys/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#![doc(html_root_url = "https://github.com/STEllAR-GROUP/hpx-rs")]
#![allow(bad_style, non_camel_case_types, unused_extern_crates)]
#![allow(dead_code, unused_imports)]
#![feature(vec_into_raw_parts)]

#[cxx::bridge]
pub mod ffi {
Expand Down Expand Up @@ -39,9 +40,45 @@ pub mod ffi {
// Wrapper for the above Bindings.
// reffer to tests to understand how to use them. [NOTE: Not all bindings have wrapper.]
// ================================================================================================
use std::ffi::CString;
Copy link
Contributor

@pingu-73 pingu-73 Oct 16, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Connor-GH can you explain why have you removed std::ffi::String?

I would really prefer not to pass this function pointer through by another static variable, but it was the only way I could find to keep the API of fn(Vec) to the user. It feels really bad, please work with me on fixing this.

  • CString in Rust is a better approach, and it eliminate the need for the c_init function and the static variable.
  • or ig instead of static variable you can use closure like the following
pub fn init<F>(func: F, func_args: Vec<String>) -> i32
where
    F: Fn(Vec<String>) -> i32 + 'static,
{
    let c_init = ......
    ....
    ...
}

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please explain what you mean by "you can use closure". A closure cannot be cast into a function pointer if it takes any arguments.

use std::env::Args;
use std::ffi::{CString, CStr};
use std::os::raw::c_char;

static mut FUNC_HOLDER: Option<fn (Vec<String>) -> i32> = None;

// Convert arguments from *mut *mut c_char to Vec<String>
// and call the saved Rust version of the function.
fn c_init(argc: i32, argv: *mut *mut c_char) -> i32 {
let mut vec_args: Vec<String> = Vec::new();

for i in 0..argc {
// SAFETY: We get the argv from a conversion from Vec<String>.
// The conversion, which is safe, perserves the arguments.
// Therefore, no null pointers.

let c_str: &CStr = unsafe { CStr::from_ptr(*argv.offset(i as isize)) };
let string = c_str.to_string_lossy().into_owned();
vec_args.push(string.to_string());
}

unsafe { FUNC_HOLDER.unwrap()(vec_args) }
}

pub fn init(func: fn(Vec<String>) -> i32, func_args: Vec<String>) -> i32
{
unsafe { FUNC_HOLDER = Some(func) };
let str_args: Vec<&str> = func_args
.iter()
.map(|s| s.as_str())
.collect::<Vec<&str>>();
let (argc, rust_argv) = create_c_args(&str_args);
let argv = rust_argv.into_raw_parts().0;

unsafe {
return self::ffi::init(c_init, argc, argv);
}
}
Comment on lines +47 to +80
Copy link
Contributor

@pingu-73 pingu-73 Oct 16, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please explain what you mean by "you can use closure". A closure cannot be cast into a function pointer if it takes any arguments.

remove the static mut variable and replace it with boxed closure to store callback. use lifetime with closure because it needs to live until explicitly freed.
refer(not boxed in it): #15 (comment)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we really need the FUNC_HOLDER? Can we not be a bit more barbaric and construct vec_args within here? This makes the FUNC_HOLDER go away at no cost.

The need to have a static variable global to this file is more of a burden to verify with the best practices and I intend to just go around it until I know better.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You cannot put the c_init function inside of the rust init function because it captures the dynamic environment (the Vec function pointer). You cannot use a closure because that's not what the FFI allows. So the only way to do this is as follows (in pseudocode):

fn some_rust_callback(argc: i32, argv: *mut *mut c_char) -> i32 {
let args = c_args_to_vec(argc, argv);
return rust_func(args); // this is the problem! how do we get this function in scope?
}

fn rust_init(rust_func: fn(Vec<String>) -> i32, args: Vec<String>) -> i32 {
let (argc, argv) = vec_to_c_args(args);
return self::ffi::init(some_rust_callback, argc, argv);
}


pub fn create_c_args(args: &[&str]) -> (i32, Vec<*mut c_char>) {
let c_args: Vec<CString> = args.iter().map(|s| CString::new(*s).unwrap()).collect();
let ptrs: Vec<*mut c_char> = c_args.iter().map(|s| s.as_ptr() as *mut c_char).collect();
Expand Down
Loading