2016-07-01 84 views
0

我在Windows 7上使用Python Ctypes訪問C++ DLL。我有DLL的文檔,但實際上無法打開它。我試圖使用一個C++函數,它接受一個函數,該函數又接受一個unsigned int和一個void指針。這是一個失敗的短代碼示例:Ctypes - 從Python傳遞無效指針

import ctypes 
import os 

root = os.path.dirname(__file__) 
lib = ctypes.WinDLL(os.path.join(root, 'x86', 'toupcam.dll')) #works 

cam = lib.Toupcam_Open(None) #works 

def f(event, ctx): #Python version of function to pass in 
    pass 

#converting Python function to C function: 
#CFUNTYPE params: return type, parameter types 
func = ctypes.CFUNCTYPE(None, ctypes.c_uint, ctypes.c_void_p)(f) 

res = lib.Toupcam_StartPullModeWithCallback(cam, func) #fails 

每當我運行此代碼,我得到的最後一行此錯誤:

OSError: exception: access violation writing 0x002CF330. 

我真的不知道如何處理這個問題,因爲這是一個C++錯誤,不是Python錯誤。我認爲它與我的void指針有關,因爲我在C++中發現的類似錯誤是與指針相關的。 Ctypes void指針有什麼問題,或者我做錯了什麼?

+1

快速谷歌顯示,'Toupcam_StartPullModeWithCallback'有三個參數:相機,回調,上下文。 http://www.webastro.net/forum/archive/index.php/t-138355.html – kfsone

回答

0

您需要聲明使用argtypes調用的函數的參數類型。因爲我不知道你的確切API,這裏有一個例子:

Windows的C DLL代碼回調:

typedef void (*CB)(int a); 

__declspec(dllexport) void do_callback(CB func) 
{ 
    int i; 
    for(i=0;i<10;++i) 
     func(i); 
} 

Python代碼:

from ctypes import * 

# You can use as a Python decorator. 
@CFUNCTYPE(None,c_int) 
def callback(a): 
    print(a) 

# Use CDLL for __cdecl calling convention...WinDLL for __stdcall. 
do_callback = CDLL('test').do_callback 
do_callback.restype = None 
do_callback.argtypes = [CFUNCTYPE(None,c_int)] 

do_callback(callback) 

輸出:

0 
1 
2 
3 
4 
5 
6 
7 
8 
9