cbindgen icon indicating copy to clipboard operation
cbindgen copied to clipboard

The ability to generate trait methods using types

Open PuffyWithEyes opened this issue 1 year ago • 1 comments

When writing similar code now:

pub trait DummyTrait {
    type DummyIn;
    type DummyOut;

    extern "C" fn dummy(self, in_: Self::DummyIn) -> Self::DummyOut;
}

#[repr(C)]
pub struct Dummy0 {
    dummy: usize,
}

impl DummyTrait for Dummy0 {
    type DummyIn = usize;
    type DummyOut = Self;

    #[unsafe(export_name = "dummy_Dummy0")]
    extern "C" fn dummy(self, in_: Self::DummyIn) -> Self::DummyOut {
        Self {
            dummy: in_,
        }
    }
}

#[repr(C)]
pub struct Dummy1 {
    dummy: usize
}

impl DummyTrait for Dummy1 {
    type DummyIn = ();
    type DummyOut = i32;

    #[unsafe(export_name = "dummy_Dummy1")]
    extern "C" fn dummy(self, in_: Self::DummyIn) -> Self::DummyOut {
        0
    }
}

Incorrect code will be generated, looking something like this:

#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>

typedef struct {
  uintptr_t dummy;
} Dummy0;

typedef struct {
  uintptr_t dummy;
} Dummy1;

DummyOut dummy_Dummy0(Dummy0 self, DummyIn in_);

DummyOut dummy_Dummy1(Dummy1 self, DummyIn in_);

My fix allows the code to be generated correctly:

#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>

typedef struct {
  uintptr_t dummy;
} Dummy0;

typedef struct {
  uintptr_t dummy;
} Dummy1;

Dummy0 dummy_Dummy0(Dummy0 self, uintptr_t in_);

int32_t dummy_Dummy1(Dummy1 self);

PuffyWithEyes avatar Feb 17 '25 18:02 PuffyWithEyes