簡體   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