Skip to content

Commit 1fddcce

Browse files
committed
Use PyCapsule in _imagingtk
1 parent f1c54f0 commit 1fddcce

File tree

2 files changed

+20
-14
lines changed

2 files changed

+20
-14
lines changed

src/PIL/ImageTk.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -48,18 +48,18 @@ def _get_image_from_kw(kw: dict[str, Any]) -> ImageFile.ImageFile | None:
4848

4949

5050
def _pyimagingtkcall(
51-
command: str, photo: PhotoImage | tkinter.PhotoImage, id: int
51+
command: str, photo: PhotoImage | tkinter.PhotoImage, ptr: object
5252
) -> None:
5353
tk = photo.tk
5454
try:
55-
tk.call(command, photo, id)
55+
tk.call(command, photo, ptr)
5656
except tkinter.TclError:
5757
# activate Tkinter hook
5858
# may raise an error if it cannot attach to Tkinter
5959
from . import _imagingtk
6060

6161
_imagingtk.tkinit(tk.interpaddr())
62-
tk.call(command, photo, id)
62+
tk.call(command, photo, repr(ptr))
6363

6464

6565
# --------------------------------------------------------------------
@@ -181,7 +181,7 @@ def paste(self, im: Image.Image) -> None:
181181
block = image.new_block(self.__mode, im.size)
182182
image.convert2(block, image) # convert directly between buffers
183183

184-
_pyimagingtkcall("PyImagingPhoto", self.__photo, block.id)
184+
_pyimagingtkcall("PyImagingPhoto", self.__photo, block.ptr)
185185

186186

187187
# --------------------------------------------------------------------
@@ -255,9 +255,8 @@ def __str__(self) -> str:
255255
def getimage(photo: PhotoImage) -> Image.Image:
256256
"""Copies the contents of a PhotoImage to a PIL image memory."""
257257
im = Image.new("RGBA", (photo.width(), photo.height()))
258-
block = im.im
259258

260-
_pyimagingtkcall("PyImagingPhotoGet", photo, block.id)
259+
_pyimagingtkcall("PyImagingPhotoGet", photo, im.im.ptr)
261260

262261
return im
263262

src/Tk/tkImaging.c

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -57,18 +57,25 @@ static Tk_PhotoPutBlock_t TK_PHOTO_PUT_BLOCK;
5757
static Imaging
5858
ImagingFind(const char *name) {
5959
Py_ssize_t id;
60+
PyObject *capsule;
61+
size_t name_len = strlen(name);
62+
const char *expected = "<capsule object \"" IMAGING_MAGIC "\" at 0x";
6063

61-
/* FIXME: use CObject instead? */
62-
#if defined(_WIN64)
63-
id = _atoi64(name);
64-
#else
65-
id = atol(name);
66-
#endif
67-
if (!id) {
64+
if (strncmp(name, expected, strlen(expected)) ||
65+
strncmp(name + name_len - 1, ">", 1)) {
66+
return NULL;
67+
}
68+
69+
capsule = (PyObject *)strtoull(name + strlen(expected), NULL, 16);
70+
71+
if (!PyCapsule_IsValid(capsule, IMAGING_MAGIC)) {
72+
PyErr_Format(
73+
PyExc_TypeError, "Expected PyCapsule with '%s' name.", IMAGING_MAGIC
74+
);
6875
return NULL;
6976
}
7077

71-
return (Imaging)id;
78+
return (Imaging)PyCapsule_GetPointer(capsule, IMAGING_MAGIC);
7279
}
7380

7481
static int

0 commit comments

Comments
 (0)