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

Can't use raw pointers #9

Closed
Michael-F-Bryan opened this issue Jan 13, 2020 · 1 comment
Closed

Can't use raw pointers #9

Michael-F-Bryan opened this issue Jan 13, 2020 · 1 comment

Comments

@Michael-F-Bryan
Copy link

I'm guessing this is just a case of things not being implemented yet, but what is required to let C functions return raw pointers?

For example this code

use std::os::raw::c_char;

#[cxx::bridge]
mod ffi {
    extern "C" {
        include!("vendor/bzip2/bzlib.h");

        fn BZ2_bzlibVersion() -> *const c_char;
    }
}

Fails to compile with

   Compiling cxx-experiment v0.1.0 (/home/michael/Documents/cxx-experiment)
error: unsupported type
 --> src/lib.rs:8:34
  |
8 |         fn BZ2_bzlibVersion() -> *const c_char;
  |                                  ^^^^^^^^^^^^^

warning: unused import: `std::os::raw::c_char`
 --> src/lib.rs:1:5
  |
1 | use std::os::raw::c_char;
  |     ^^^^^^^^^^^^^^^^^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

error: aborting due to previous error
error: could not compile `cxx-experiment`.
To learn more, run the command again with --verbose.
@dtolnay
Copy link
Owner

dtolnay commented Jan 13, 2020

So far I am not decided on supporting raw pointers, but currently leaning against. I'd like to see if we can instead specialize toward interfaces that are structured to make it possible to always decide "is this code correct" without looking at the other language.

So in the context of your use case in https://github.com/Michael-F-Bryan/cxx-experiment/blob/1695c0f0d74f045ebfd0565a4d33d9b3222ccb03/src/lib.rs maybe something like one of these options:

#[cxx::bridge]
mod ffi {
    extern "C" {
        fn bzlib_version_equals(expected: &str) -> bool;
    }
}

// c++
bool bzlib_version_equals(RustStr expected) {
  auto actual = BZ2_bzlibVersion();
  return strncmp(actual, expected.data(), expected.size()) == 0
      && actual[expected.size()] == '\0';
}

// rust
assert!(ffi::bzlib_version_equals("1.0.8, 13-Jul-2019"));
#[cxx::bridge]
mod ffi {
    extern "C" {
        fn bzlib_version() -> String;
    }
}

// c++
RustString bzlib_version() {
  return RustString(BZ2_bzlibVersion());
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants