Skip to content

Conversation

@VanshAgarwal24036
Copy link
Contributor

@VanshAgarwal24036 VanshAgarwal24036 commented Jan 21, 2026

It fixes a crash in ctypes that occur when a deprecated POINTER(str) type was used in argtypes.

When such a pointer type was encountered during argument conversion, ctypes would hit an internal assertion and abort the interpreter in debug builds.
This PR replaces the assertion with proper error handling and raises a Python exception instead.

@VanshAgarwal24036

This comment was marked as resolved.

@VanshAgarwal24036
Copy link
Contributor Author

@vstinner This is my proposed solution if you have time please review it.

Comment on lines 478 to 479
with self.assertWarns(DeprecationWarning):
BadType = ctypes.POINTER("BugTrigger")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would prefer to avoid deprecated code path. You should be able to use:

Suggested change
with self.assertWarns(DeprecationWarning):
BadType = ctypes.POINTER("BugTrigger")
class BadType(ctypes._Pointer):
# _type_ is not defined on purpose
pass

Comment on lines 481 to 488
if os.name == "nt":
libc = ctypes.WinDLL("kernel32.dll")
func = libc.GetCurrentProcessId
else:
libc = ctypes.CDLL(None)
func = libc.getpid

func.argtypes = (BadType,)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can use the Python C API:

Suggested change
if os.name == "nt":
libc = ctypes.WinDLL("kernel32.dll")
func = libc.GetCurrentProcessId
else:
libc = ctypes.CDLL(None)
func = libc.getpid
func.argtypes = (BadType,)
func = ctypes.pythonapi.Py_GetVersion
func.argtypes = (BadType,)

ptr.set_type(c_int)
self.assertIs(ptr._type_, c_int)

class TestPointerStringProto(unittest.TestCase):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would prefer to add the test to the end of PointersTestCase, instead of adding a new test case.

import gc
import sys
import unittest
import os
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This import can be removed with my proposed code.

VanshAgarwal24036 and others added 5 commits January 23, 2026 23:14
Co-authored-by: Victor Stinner <vstinner@python.org>
Co-authored-by: Victor Stinner <vstinner@python.org>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants