Is there a way to choose the scope of the generated code with Rust macros?

Viewed 38

Suppose I have the following code:

struct Example;

impl Example {
    #[my_attr_macro]
    fn method() -> Self {
        Self;
    }
}

I want to generate a function that will eventually call this method in its body. I am able to generate such a function already but it's placed inside the impl block. Is there any way to generate on the outer scope of the impl block?

This outer function will be called from C code so it has use C ABI and it must have a specific name (which I will also generate) to work.

1 Answers

Generally no. But if all you want is to access it via FFI, then you can export it with this name to the C code by using #[no_mangle]:

impl Example {
    #[my_attr_macro]
    pub fn method() -> Self {
        #[no_mangle]
        extern "C" fn ffi_function() {}
    }
}

Now Rust code will not be able to call ffi_function(), but C code will be able to link against it (and of course Rust code too).

Related