Or maybe, I shouldn't cast. Here's what I'm doing:
I'm writing a piece of code that links a Linux device driver to a higher level library. The authors of the library use void *
(under a new name via typedef
) to store handles to an implementation specific object that describes a communication channel.
The driver I want to connect with the library uses int
to store handles to its channels (because they are file descriptors as returned by calls to open()
). So, in my code, I get void *
passed in from the library and need to call stuff from the driver using an int
and vice versa. I. e.:
// somewhere in the library ...
typedef void* CAN_HANDLE;
// ... in my code
CAN_HANDLE canOpen_driver(s_BOARD *board)
{
int fd;
// ...
fd = open(busname, O_RDWR);
// ...
return (CAN_HANDLE) fd; // <-- not safe, especially not when converting back.
}
The adapters that others have written actually store some struct etc. somewhere and just cast between pointers, so no size issues arise. In my case, I don't really want to manage file descriptors, as the OS already does.
On my PC, I think the pointer is larger than the int
, so I could bit-twiddle my way out of this, but the code goes into embedded systems, too, and I'm not experienced enough to make any assumptions about the size of types on those machines.