繁体   English   中英

如何在python3中使用ctypes void **指针

[英]How to use ctypes void ** pointer in python3

我将通过它的DLL连接一个光谱仪,其中一个功能定义为

UINT UAI_SpectrometerOpen(unsigned int dev, void** handle, unsigned int VID,  unsigned int PID)

从文档开始,dev是指定光谱仪句柄的索引是返回光谱仪句柄的指针VID是提供指定的VID PID是提供指定的PID dev,VID,PID是已知的,但我不知道如何设置句柄。 我当前的代码是

import ctypes
otoDLL = ctypes.CDLL('UserApplication.dll')
spectrometerOpen = otoDLL.UAI_SpectrometerOpen
spectrometerOpen.argtypes = (ctypes.c_uint, ctypes.POINTER(c_void_p),
                         ctypes.c_uint, ctypes.c_uint)
spectrometerOpen.restypes = ctypes.c_uint
handle = ctypes.c_void_p
errorCode = spectrometerOpen(0, handle, 1592, 2732)

当我运行以上代码时,出现错误

runfile('C:/Users/Steve/Documents/Python Scripts/otoDLL.py', wdir='C:/Users/Steve/Documents/Python Scripts')
Traceback (most recent call last):

  File "<ipython-input-1-73fe9922d732>", line 1, in <module>
    runfile('C:/Users/Steve/Documents/Python Scripts/otoDLL.py', wdir='C:/Users/Steve/Documents/Python Scripts')

  File "C:\Users\Steve\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 685, in runfile
    execfile(filename, namespace)

  File "C:\Users\Steve\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 85, in execfile
    exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)

  File "C:/Users/Steve/Documents/Python Scripts/otoDLL.py", line 5, in <module>
    spectrometerOpen.argtypes = (ctypes.c_uint, ctypes.POINTER(c_void_p),

NameError: name 'c_void_p' is not defined

我对ctypes和C不熟悉,谁能帮助我解决此问题。 非常感谢。

根据您的错误输出:

  File "C:/Users/Steve/Documents/Python Scripts/otoDLL.py", line 5, in <module>
    spectrometerOpen.argtypes = (ctypes.c_uint, ctypes.POINTER(c_void_p),

您忘记将ctypes放在c_void_p之前,因此:

spectrometerOpen.argtypes = (ctypes.c_uint, ctypes.POINTER(ctypes.c_void_p),
                         ctypes.c_uint, ctypes.c_uint)

根据您的函数签名,handle参数是一个指向void*的指针,因此您需要像这样传递它:

import ctypes
otoDLL = ctypes.CDLL('UserApplication.dll')
spectrometerOpen = otoDLL.UAI_SpectrometerOpen
spectrometerOpen.argtypes = (ctypes.c_uint, ctypes.POINTER(ctypes.c_void_p),
                         ctypes.c_uint, ctypes.c_uint)
spectrometerOpen.restypes = ctypes.c_uint

# declare HANDLE type, which is a void*
HANDLE = ctypes.c_void_p

# example: declare an instance of HANDLE, set to NULL (0)
my_handle = HANDLE(0)

#pass the handle by reference (works like passing a void**)
errorCode = spectrometerOpen(0, ctypes.byref(my_handle), 1592, 2732)

注意:这仅是一个示例,您应该查看spectrometerOpen函数的文档,以查看其正真正等待handle参数的内容(可以为NULL,其确切类型是什么,等等)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM