With the libusb library the `libusb_get_device_lis...
# kotlin-native
n
With the libusb library the
libusb_get_device_list
function takes a list (parameter) however the list is a container for
libusb_device
, which is a opaque pointer. Is there a way to allocate a opaque pointer? Below is the function's mapping:
Copy code
public fun libusb_get_device_list(ctx: kotlinx.cinterop.CValuesRef<cnames.structs.libusb_context>?, list: kotlinx.cinterop.CValuesRef<kotlinx.cinterop.CPointerVar<kotlinx.cinterop.CPointerVar<cnames.structs.libusb_device> /* = kotlinx.cinterop.CPointerVarOf<kotlinx.cinterop.CPointer<cnames.structs.libusb_device>> */> /* = kotlinx.cinterop.CPointerVarOf<kotlinx.cinterop.CPointer<kotlinx.cinterop.CPointerVarOf<kotlinx.cinterop.CPointer<cnames.structs.libusb_device>>>> */>?): platform.posix.ssize_t /* = kotlin.Long */ { /* compiled code */ }
Below is the C example from the libusb website:
Copy code
// discover devices
libusb_device **list;
libusb_device *found = NULL;
ssize_t cnt = libusb_get_device_list(NULL, &list);
ssize_t i = 0;
int err = 0;
if (cnt < 0)
    error();
for (i = 0; i < cnt; i++) {
    libusb_device *device = list[i];
    if (is_interesting(device)) {
        found = device;
        break;
    }
}
if (found) {
    libusb_device_handle *handle;
    err = libusb_open(found, &handle);
    if (err)
        error();
    // etc
}
libusb_free_device_list(list, 1);
s
You can allocate it just like any other pointer.
a
Also trying to write
libusb
wrapper for K/N. I'm not an expert in system programming. The following code works for me:
Copy code
val devs = memScope.alloc<CPointerVar<CPointerVar<libusb_device>>>()
val count = libusb_get_device_list(null, devs.ptr)
n
Alexander - What does your def file look like? Below are the contents of the def file:
Copy code
package = usb
headers = libusb.h
linkerOpts = -L/usr/lib/x86_64-linux-gnu -lusb-1.0
compilerOpts = -I/usr/include/libusb-1.0
Does my def file look ok?
The
libusb_device
struct is seen as a unresolved reference by the Kotlin Native compiler.
Tried something a bit crazy (redefine a struct) by appending the following to the def file:
Copy code
---
struct libusb_device;
Did another compile and the crazy trick worked 😁 .
a
My `libusb.def`:
Copy code
headers = libusb.h
headerFilter = libusb.h
linkerOpts.linux = -L/usr/lib -l:libusb-1.0.so
And `build.gradle.kts`:
Copy code
compilations["main"].cinterops {
    val libusb by creating {
        includeDirs.headerFilterOnly("/usr/include/libusb-1.0")
    }
}
n
Isn't it invalid to have a colon in between -l and the library file?
In order to iterate over the device list an array would need to be allocated:
val devList = allocArray<CPointerVar<CPointerVar<libusb_device>>>(1)
116 Views