Skip to content

Commit

Permalink
Initializes FFI for ctors
Browse files Browse the repository at this point in the history
  • Loading branch information
ultimaweapon committed Oct 19, 2024
1 parent 31e2045 commit a429e00
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 10 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ The goal of this crate is to allows efficient integration between Rust and C++,
## Limitations

- Rust cannot access an instance variable directly. You need to create a getter/setter for each variable you want to access.
- Inline method is not supported. That mean you cannot define a method you want to use inside a class declaration.

## Usage

Expand Down
17 changes: 10 additions & 7 deletions example/src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,18 @@

class class1 {
public:
class1()
{
}

class1(const char *v1) : v1(v1)
{
}
class1();
class1(const char *v1);
protected:
std::string v1;
};

CPPBIND_CLASS(class1);

class1::class1()
{
}

class1::class1(const char *v1) : v1(v1)
{
}
21 changes: 18 additions & 3 deletions macros/src/cpp.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use self::class::Class;
use crate::META;
use proc_macro2::{Literal, TokenStream};
use proc_macro2::{Literal, Span, TokenStream};
use quote::{format_ident, quote};
use syn::parse::{Parse, ParseStream};
use syn::Error;
Expand Down Expand Up @@ -57,10 +57,10 @@ fn render_class(item: Class) -> syn::Result<TokenStream> {
}
};

// Render constructors.
// Render constructor wrappers.
let mut impls = TokenStream::new();

for (i, ctor) in item.ctors.into_iter().enumerate() {
for (i, ctor) in item.ctors.iter().enumerate() {
let name = format_ident!("new{}", i + 1, span = ctor.span);

impls.extend(quote! {
Expand All @@ -73,6 +73,19 @@ fn render_class(item: Class) -> syn::Result<TokenStream> {
});
}

// Render constructor FFI.
let mut externs = TokenStream::new();

for (i, ctor) in item.ctors.iter().enumerate() {
let name = format_ident!("{}_new{}", class, i + 1, span = Span::call_site());

externs.extend(quote! {
unsafe extern "C-unwind" {
fn #name(this: *mut ());
}
});
}

// Compose.
let align = Literal::usize_unsuffixed(align);
let mem = if name.chars().next().unwrap().is_uppercase() {
Expand Down Expand Up @@ -111,6 +124,8 @@ fn render_class(item: Class) -> syn::Result<TokenStream> {
Self::new()
}
}

#externs
})
}

Expand Down

0 comments on commit a429e00

Please sign in to comment.