This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: ctypes: Returning c_void_p from callback doesn\'t work
Type: Stage:
Components: Library (Lib) Versions: Python 2.5
process
Status: closed Resolution: works for me
Dependencies: Superseder:
Assigned To: theller Nosy List: albertstrasheim, theller
Priority: normal Keywords:

Created on 2006-10-10 15:18 by albertstrasheim, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (2)
msg30206 - (view) Author: Albert Strasheim (albertstrasheim) Date: 2006-10-10 15:18
C code:

extern CALLBACK_API void* foo(void*(*callback)()) {
    printf("foo calling callback\n");
    callback();
    printf("callback returned in foo\n");
}

callback.py contains:

import sys
print sys.version
from ctypes import *
def callback(*args):
    return c_void_p()
#lib = cdll['libcallback.so']
lib = cdll['callback.dll']
lib.foo.argtypes = [CFUNCTYPE(c_void_p)]
lib.foo(lib.foo.argtypes[0](callback))

With Python 2.4.3 and ctypes 1.0.0 + Thomas Heller's
patch for another issue (which doesn't seem to affect
this situation, but anyway) I get the following error:

2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit
(Intel)]
foo calling callback
Traceback (most recent call last):
  File "source/callbacks.c", line 216, in 'converting
callback result'
TypeError: cannot be converted to pointer
Exception  in None ignored
callback returned in foo

With Python 2.5 and ctypes 1.0.1 I get:

2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32
bit (Intel)]
foo calling callback
Traceback (most recent call last):
  File "\loewis\25\python\Modules\_ctypes\callbacks.c",
line 216, in
'converting callback result'
TypeError: cannot be converted to pointer
Exception  in <function callback at 0x009C3CF0> ignored
callback returned in foo

Returning a Python integer from callback() doesn't
cause an error to be raised.
msg30207 - (view) Author: Thomas Heller (theller) * (Python committer) Date: 2007-01-09 20:50
Sorry for the late reply, and I hope you are still interested in this.

Basically, when you return something from the callback, ctypes does the same as if you would do this "c_void_p(something)".   Now, you cannot construct a c_void_p instance from a c_void_p instance, you get exactly the same error as you mention above:

>>> c_void_p(c_void_p(42))
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: cannot be converted to pointer
>>>

I'm not sure if this should be considered a bug or not, anyway there is an easy workaround:  Return an integer from the callback, or, if you have a c_void_p instance, the .value attribute thereof.

I think this should not be fixed.
History
Date User Action Args
2022-04-11 14:56:20adminsetgithub: 44111
2006-10-10 15:18:17albertstrasheimcreate