How to set return type for std::pair<char*, char*>?

Hi folks,

I added c++ library to my Rust code and one of the c++ function returns std::pair<char*, char*>.
Could somebody advice what return type should I set in Rust code for the linked function to return the same result ?

extern "C" {
    #[link(name="srp6_dir", kind="static")]
    fn test_srp6(B_str: *const c_char, s_str: *const c_char, account_str: *const c_char) -> (c_char, c_char);
}

// actual output
-96, -92
// expected output
"0314DAEE67C1704DE25DF706A750060AAF4B745D06EA67F8B4BB7920A8E935A9DF12C329EA930469", "A82AF66EBE6F57B31F386E97376B8DF626AC8FCB"

the c++ function is declared like this:

extern "C" std::pair<char*, char*> test_srp6(const char* B_str, const char* s_str, const char* account_str) {
// ...
}

This is a C++ type so it can't be used safely/accurately with Rust. You can only use types that conform to the C ABI. For example, you could convert it to a C struct containing the two values, and return that.

For more see the Rust FFI.

3 Likes

Thank you very much, this helps

That's not 100% true. While there are no portable way to do that most real C++ platforms have stable ABI.

Which means that it's possible to pass C++ types, but that's very non-trivial: you have to study documentation for a particular compiler that you use and also for a particular standard C++ library, too!

One very instructive example: while std::pair<const chat*, const char*> is passed like struct with two fields but std::tuple<const chat*, const char*> is passed differently depending on whether you use libc++ or libstdc++!

That essentially means that you need to do that on per-target basis and keep unittests that verify that everything is passed like you expect it to be passed.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.