Newtype and C binding

#1

Hi,

I have a Rust API that is C-callable e.g.

The parameters CommandHandle and WalletHandle are i32.

Now I want these types to be newtypes that is I replace

type WalletHandle = i32;

by

#[derive(Debug, Hash, PartialEq, Eq, Copy, Clone)]
pub struct WalletHandle(pub i32);

Does Rust guarantee that the C-API does not change? Or do I need a repr© for the newtype, or something?

thanks
Axel

#2

You need to add #[repr(transparent)]

1 Like
#3

Like so https://github.com/AxelNennker/indy-sdk/blob/WalletHandle/libindy/src/api/mod.rs#L23 >

#[repr(transparent)]
#[derive(Debug, Hash, PartialEq, Eq, Copy, Clone)]
pub struct WalletHandle(pub i32);

#4

Yup, that’s it!

#5

Thank you.

Maybe add this to the documentation of newtype?
From https://doc.rust-lang.org/1.26.2/unstable-book/language-features/repr-transparent.html

The attribute can be applied to a newtype-like structs that contains a single field. It indicates that the newtype should be represented exactly like that field’s type, i.e., the newtype should be ignored for ABI purpopses: not only is it laid out the same in memory, it is also passed identically in function calls.

#6

You’ve linked to an old unstable version of feature documentation. The up to date documentation is at https://doc.rust-lang.org/stable/reference/type-layout.html#the-transparent-representation

#7

I find the older documentation clearer in relation to newtype because it clearly says: If you want the newtype exactly for type safety the repr transparent is what you what because memory layout and c-api calls are the them.
The current documentation means the same but there is no relation to the newtype pattern.
In fact the word newtype does is only once found in the current documentation. Does the newtype pattern have a new name?