2014-09-04 76 views
1
from ctypes import * 
class CTest(Structure): 
    pass 

def get_test(id): 
    c = CTest() 
    return c 

func_type = CFUNCTYPE(CTest, c_int) 
test_callback = func_type(get_test) 

當我運行該腳本,我得到:Python的ctypes回調函數可以返回一個python類的實例嗎?

Traceback (most recent call last): 
    File "E:\test\ctypes_test.py", line 11, in <module> 
    test_callback = func_type(get_test) 
TypeError: invalid result type for callback function 

什麼是錯的腳本?

+0

就像一張紙條:它是一個不好的做法'進口*'。你應該'輸入ctypes',輸入'ctypes.Structure'可能會花費更多的精力,但是你知道它來自ctypes模塊,這有助於避免混淆 – Apoorv 2014-09-04 11:39:39

回答

0

使用ctypes.pyobject

import ctypes 
#from ctypes import * 
class CTest(ctypes.Structure): 
    _fields_ = [] 
    a = 10 

    def __init__(self): 
     ctypes.Structure.__init__(self) 

def get_test(id): 
    return CTest() 


func_type = ctypes.CFUNCTYPE(ctypes.py_object , ctypes.c_int) 
test_callback = func_type(get_test) 

print test_callback(1).a 

>> 10

相關問題