Working with `PyQt5.QtCore.QLibrary` in Python: How to cast a `sip.voidptr` to a function?

768 Views Asked by At

I am trying to port (some of) the logic of void QgsPluginManager::getCppPluginsMetadata() from QGIS from C++ to Python.

In C++, the relevant section looks about as follows:

/* `lib` is a path (string) to a QGIS plugin shared object file, e.g. `/lib/qgis/plugins/libtopolplugin.so` */
QLibrary *myLib = new QLibrary( lib );
bool loaded = myLib->load();
if ( !loaded ) { /* handle error */ }
name_t *pName = ( name_t * ) cast_to_fptr( myLib->resolve( "name" ) );
if ( pName ) { QgsDebugMsg( "Plugin name: " + pName() ); }

QLibrary is used to load the shared object file. Once it is loaded, function pointers are resolved, casted to actual functions and then called. In the above example, pName would return the name of the plugin as a string.

In Python, tried the following:

import sys
from PyQt5 import QtCore

lib = '/lib/qgis/plugins/libtopolplugin.so'
myLib = QtCore.QLibrary(lib)

loaded = myLib.load()
if not loaded:
    print("Failed to load library!")
    sys.exit()

print( myLib.resolve( "name" ) )
print( myLib.resolve( "name" )() )

print('The end.')

I got the following output:

<sip.voidptr object at 0x7fa046b214b0>
Traceback (most recent call last):
  File "test_QLibrary.py", line 17, in <module>
    print( myLib.resolve( "name" )() )
TypeError: 'sip.voidptr' object is not callable

It makes sense that I can not call a sip.voidptr directly - I'd need to cast it to a function somehow. Is this even possible (with sip or other tools) in Python? If yes, how?

0

There are 0 best solutions below