在Python中使用'PyQt5.QtCore.QLibrary':如何将'sip.voidptr'强制转换为函数?

2024-09-28 22:23:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从QGIS中从C++到Python端口中的一些逻辑({ a1})。

在C++中,相关章节的内容如下:

/* `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用于加载共享对象文件。一旦加载,函数指针将被解析、转换为实际函数,然后被调用。在上面的示例中,pName将以字符串形式返回插件的名称

在Python中,尝试了以下操作:

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.')

我得到了以下输出:

<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

我不能直接调用sip.voidptr,这是有道理的——我需要以某种方式将它转换为函数。在Python中(使用sip或其他工具)这是可能的吗?如果是,如何进行


Tags: tonameifobjectlibloadresolveprint