Skip to content

[docs] Improve CxxString example with various usage patterns #1190

Open
@nyurik

Description

@nyurik

I am new to the Rust-C++ FFI, and have been trying to adapt it to one of our projects. I have been going over the CxxString docs, trying to understand the best usage pattern. I think it could be improved with a few more code examples. I would love to contribute to the docs/book, but will need to understand it first. I do think that the Json example gets a little in the way of answering a simple question of "given this existing C++ API that uses std::string, this is how to call it", but that could be just me.

Given this C++ function, I need to either add some extra C++ code to work around the limitations of no-by-value passing, or some other steps:

// key is passed by value, it is not modified by the function
// value is passed by ref, it receives some output
int32_t GetValue(std::string key, std::string& value);

By-value limitation

Apparently @schreter is working on this in #1185 (thank you!!! I would love to participate), so might be relevant here.
To work around the by-value limitation, my understanding is that i may need to create a wrapper C++ function. This seems a bit strange that C++ allows me to silently cast by ref to by val, but I haven't worked with it for a while, might be a bit ... "rusty".

int32_t GetValue2(const std::string& key, std::string& value) {
  return GetValue(key, value);
}

Calling C++ function from Rust

This is what I would have expected to use, but it does not even begin to compile, so a bit lost with pinning and other magic.

let_cxx_string!(key = "example");
let_cxx_string!(value = "");
let res = crate::ffi::GetValue2(key, value);  // may need some modifiers like &key ?
println!("res = {res}, key = {key}, value = {value}");  // may need some key/value unwrapping

Thank you!!!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions