简体   繁体   中英

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

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM