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

I wonder how to use "cxx" with 3rd C++ interface? #72

Closed
dbsxdbsx opened this issue Mar 17, 2020 · 2 comments
Closed

I wonder how to use "cxx" with 3rd C++ interface? #72

dbsxdbsx opened this issue Mar 17, 2020 · 2 comments

Comments

@dbsxdbsx
Copy link

Let me make it clear. I got a project which need to use a 3rd C++ library(with lib and header).
To use it , I have to do so in C++:

#include <"ThirdPartyInterface.h">
class CMyClass: public ThirdPartyInterface{
virtual callbackFrom3rdPartyInterface();// I need to implement it. 
};
@dtolnay
Copy link
Owner

dtolnay commented Mar 17, 2020

If you want to use Rust logic to implement the interface required by the C++ library, it would be something like this:

  • lib.rs:

#[cxx::bridge]
mod ffi {
    extern "C" {
        include!("cmyclass.h");

        type CMyClass;

        // plus, optionally, any accessors that Rust needs to access fields
        // of the opaque type CMyClass
    }

    extern "Rust" {
        fn c_my_class_callback(this: &mut CMyClass);
    }
}

fn c_my_class_callback(this: &mut ffi::CMyClass) {
    // the implementation
    println!("it works");
}
  • cmyclass.h:

#include "ThirdPartyInterface.h"

class CMyClass : public ThirdPartyInterface {
  void callbackFrom3rdPartyInterface() override;
};
  • cmyclass.cc:

#include "cmyclass.h"
#include "lib.rs"

void CMyClass::callbackFrom3rdPartyInterface() {
  c_my_class_callback(*this);
}

@dtolnay dtolnay closed this as completed Apr 8, 2020
@dbsxdbsx
Copy link
Author

dbsxdbsx commented Apr 8, 2020

@dtolnay, thanks.

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