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] increase the refcount of a callback function
Type: enhancement Stage:
Components: ctypes Versions: Python 3.10
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: Zuzu_Typ, amaury.forgeotdarc, belopolsky, eryksun, meador.inge, pablogsal
Priority: normal Keywords:

Created on 2018-05-02 06:39 by Zuzu_Typ, last changed 2022-04-11 14:59 by admin.

Messages (2)
msg316047 - (view) Author: (Zuzu_Typ) Date: 2018-05-02 06:39
It should be considered to increase the refcount of functions that are passed on to an external library at some point.

If this is not done and e.g. the function was a local variable, when leaving the scope it gets garbage-collected. When the library now tries to execute said function, an access violation occurs.

So if the refcount were increased either upon creating the CFUNCTYPE instance or when it's passed on, this could be avoided.
msg316057 - (view) Author: Eryk Sun (eryksun) * (Python triager) Date: 2018-05-02 09:16
There isn't a problem in most cases, since functions that take a callback usually call it before returning. If the library does keep a long-lived reference to a callback (e.g. a console control handler in Windows), there are ways to support this, depending on the context (e.g. global variable, class attribute, instance attribute, a dict). 

However, for the case where a callback should remain referenced for the lifetime of the process, it would be convenient to have a `callback_incref` option. Internally this would use a new function flag `FUNCFLAG_CALLBACK_INCREF`.
History
Date User Action Args
2022-04-11 14:59:00adminsetgithub: 77587
2021-03-28 03:07:14eryksunsetversions: + Python 3.10, - Python 3.7, Python 3.8
2019-03-20 10:44:43cheryl.sabellasetnosy: + pablogsal
2018-05-02 09:16:40eryksunsetnosy: + eryksun
title: [ctypes] increase refcount of a CFUNCTYPE instance when passing to a CDLL -> [ctypes] increase the refcount of a callback function
messages: + msg316057

versions: + Python 3.7, Python 3.8
type: behavior -> enhancement
2018-05-02 06:54:41ned.deilysetnosy: + amaury.forgeotdarc, belopolsky, meador.inge
2018-05-02 06:39:05Zuzu_Typcreate