https://github.com/python/cpython/commit/27ded243485670fa836c9bb421e37a6ef16eca8e
commit: 27ded243485670fa836c9bb421e37a6ef16eca8e
branch: main
author: Arjit Singh Grover <[email protected]>
committer: encukou <[email protected]>
date: 2026-02-24T13:16:58+01:00
summary:

gh-143304: Fix ctypes.CDLL to honor handle parameter on POSIX systems 
(GH-143318)

The handle parameter was being ignored in the POSIX implementation
of CDLL._load_library(), causing it to always call _dlopen() even
when a valid handle was provided. This was a regression introduced
in recent refactoring.

files:
A Misc/NEWS.d/next/Library/2026-01-01-05-26-00.gh-issue-143304.Kv7x9Q.rst
M Lib/ctypes/__init__.py
M Lib/test/test_ctypes/test_loading.py

diff --git a/Lib/ctypes/__init__.py b/Lib/ctypes/__init__.py
index aec92f3aee2472..1c822759eca912 100644
--- a/Lib/ctypes/__init__.py
+++ b/Lib/ctypes/__init__.py
@@ -458,6 +458,8 @@ def _load_library(self, name, mode, handle, winmode):
                 if name and name.endswith(")") and ".a(" in name:
                     mode |= _os.RTLD_MEMBER | _os.RTLD_NOW
             self._name = name
+            if handle is not None:
+                return handle
             return _dlopen(name, mode)
 
     def __repr__(self):
diff --git a/Lib/test/test_ctypes/test_loading.py 
b/Lib/test/test_ctypes/test_loading.py
index 3b8332fbb30928..343f6a07c0a32c 100644
--- a/Lib/test/test_ctypes/test_loading.py
+++ b/Lib/test/test_ctypes/test_loading.py
@@ -106,6 +106,14 @@ def test_load_without_name_and_with_handle(self):
         lib = ctypes.WinDLL(name=None, handle=handle)
         self.assertIs(handle, lib._handle)
 
+    @unittest.skipIf(os.name == "nt", 'POSIX-specific test')
+    @unittest.skipIf(libc_name is None, 'could not find libc')
+    def test_load_without_name_and_with_handle_posix(self):
+        lib1 = CDLL(libc_name)
+        handle = lib1._handle
+        lib2 = CDLL(name=None, handle=handle)
+        self.assertIs(lib2._handle, handle)
+
     @unittest.skipUnless(os.name == "nt", 'Windows-specific test')
     def test_1703286_A(self):
         # On winXP 64-bit, advapi32 loads at an address that does
diff --git 
a/Misc/NEWS.d/next/Library/2026-01-01-05-26-00.gh-issue-143304.Kv7x9Q.rst 
b/Misc/NEWS.d/next/Library/2026-01-01-05-26-00.gh-issue-143304.Kv7x9Q.rst
new file mode 100644
index 00000000000000..826b2e9a126d36
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-01-01-05-26-00.gh-issue-143304.Kv7x9Q.rst
@@ -0,0 +1 @@
+Fix :class:`ctypes.CDLL` to honor the ``handle`` parameter on POSIX systems.

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to