Port libusb plugin to build on python2/python3

This commit is contained in:
Eli Schwartz 2019-03-13 00:45:08 -04:00
parent 190b8c73d8
commit 1d5c89f69b

View File

@ -115,6 +115,8 @@ static PyObject* get_devices(PyObject *self, PyObject *args) {
return ans;
}
static char libusb_doc[] = "Interface to libusb.";
static PyMethodDef libusb_methods[] = {
{"get_devices", get_devices, METH_VARARGS,
"get_devices()\n\nGet the list of USB devices on the system."
@ -123,26 +125,55 @@ static PyMethodDef libusb_methods[] = {
{NULL, NULL, 0, NULL}
};
CALIBRE_MODINIT_FUNC
initlibusb(void) {
#if PY_MAJOR_VERSION >= 3
#define INITERROR return NULL
#define INITMODULE PyModule_Create(&libusb_module)
static struct PyModuleDef libusb_module = {
/* m_base */ PyModuleDef_HEAD_INIT,
/* m_name */ "libusb",
/* m_doc */ libusb_doc,
/* m_size */ -1,
/* m_methods */ libusb_methods,
/* m_slots */ 0,
/* m_traverse */ 0,
/* m_clear */ 0,
/* m_free */ 0,
};
CALIBRE_MODINIT_FUNC PyInit_libusb(void) {
#else
#define INITERROR return
#define INITMODULE Py_InitModule3("libusb", libusb_methods, libusb_doc)
CALIBRE_MODINIT_FUNC initlibusb(void) {
#endif
PyObject *m;
// We deliberately use the default context. This is the context used by
// libmtp and we want to ensure that the busnum/devnum numbers are the same
// here and for libmtp.
if(libusb_init(NULL) != 0) return;
if(libusb_init(NULL) != 0) {
INITERROR;
}
Error = PyErr_NewException("libusb.Error", NULL, NULL);
if (Error == NULL) return;
if (Error == NULL) {
INITERROR;
}
cache = PyDict_New();
if (cache == NULL) return;
if (cache == NULL) {
INITERROR;
}
m = Py_InitModule3("libusb", libusb_methods, "Interface to libusb.");
if (m == NULL) return;
m = INITMODULE;
if (m == NULL) {
INITERROR;
}
PyModule_AddObject(m, "Error", Error);
PyModule_AddObject(m, "cache", cache);
#if PY_MAJOR_VERSION >= 3
return m;
#endif
}