Python ctypes回调函数可以返回一个python类实例吗?

时间:2014-09-04 10:57:14

标签: python ctypes

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)

当我运行这个脚本时,我得到了:

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

脚本出了什么问题?

1 个答案:

答案 0 :(得分: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
  
    

<强>&GT;&GT; 10