Device shouldn't reference context
elmarco opened this issue · 7 comments
We should follow libusb more closely there.
open()
should be a method on the Context
, not on Device
. This would remove the need to track the context in Device
.
Alternatively, make open()
take a context
argument.
One of the reason is that there are cases where all you have is a libusb_device*
, without its context, and you may want to still wrap it with Device
.
Current ugly workaround... rusb::Device::from_libusb(FakeUsbContext {}, ptr)
This reference is required for memory safety -- a Device
is tied to a particular Context
and must not outlive it. Context
is reference-counted internally, so the reference from Device
keeps the Context
alive.
If you don't want to manage contexts, use GlobalContext
.
That makes sense. But it could be made optional, so you could bind devices without context, like my example (unsafe anyway).
I don't see an explicit documentation about the fact that device can't outline their context:
https://libusb.sourceforge.io/api-1.0/group__libusb__dev.html#ga77eedd00d01eb7569b880e861a971c2b
Well libusb_device
contains a libusb_context*
and pretty much any operation on it will dereference that.
https://github.com/libusb/libusb/blob/1a906274a66dd58bf81836db1306902d4a7dc185/libusb/libusbi.h#L486
But reading source code reveals that it indeed keeps a pointer to the context, without taking a ref. Bad idea, I wonder if it could be fixed in libusb.
So I close this issues because we must store reference to context