JonasLevin
JonasLevin

Reputation: 2109

Expose Rust function through FFI with c bindings

I'm creating a Rust library and want to expose my Rust functions through c bindings to Dart. This question is just related to the setup of actually exposing the Rust function through C bindings and not on how to call it in Dart.
This is my function which I want to expose through FFI:

pub fn create_channel(credential: String) -> Result<String, iota_streams::core::Error> {
    let seed = create_seed::new();

    // Create the Transport Client
    let client = Client::new_from_url(&dotenv::var("URL").unwrap());
    let mut author = Author::new(&seed, ChannelType::SingleBranch, client.clone());

    // Create the channel with an announcement message. Make sure to save the resulting link somewhere,
    let announcement_link = author.send_announce()?;

    // This link acts as a root for the channel itself
    let ann_link_string = announcement_link.to_string();

    // Author will now send signed encrypted messages in a chain
    let msg_inputs = vec![credential];

    let mut prev_msg_link = announcement_link;
    for input in &msg_inputs {
        let (msg_link, _seq_link) = author.send_signed_packet(
            &prev_msg_link,
            &Bytes::default(),
            &Bytes(input.as_bytes().to_vec()),
        )?;
        println!("Sent msg: {}", msg_link);
        prev_msg_link = msg_link;
    }
    Ok(ann_link_string)
}

The credential String is supposed to be just a stringified json object. Which I want to provide from Dart through C bindings into Rust and then use inside my create_channel function. But I don't know how to define the type of my credential parameter, because it would come in as a C type and then would need to be converted to Rust.

#[no_mangle]
pub extern "C" fn create_channel(credential: *const raw::c_char) -> String {
    streams::create_channel(credential).unwrap()
}

Right now I'm just defining the parameters of my extern function to be off type c_char but I would then need to convert this C type to a Rust String or &str. So that I can use it inside of my actual create_channel function written in Rust.

As what types should I define the credential parameter and how would I convert the c_char into a String or &str?

Upvotes: 1

Views: 472

Answers (1)

F0X
F0X

Reputation: 380

Rust has the convenient CStr and CString types, you can use Cstr::from_ptr to wrap the raw string and then call to_str on that. Of course you need to do some error handling here for cases where the string isn't valid UTF-8.

Upvotes: 1

Related Questions