Skip to content

Commit 55845f2

Browse files
committed
Use PyCapsule in _imagingtk
1 parent f1c54f0 commit 55845f2

File tree

2 files changed

+20
-15
lines changed

2 files changed

+20
-15
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 & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -56,19 +56,25 @@ static Tk_PhotoPutBlock_t TK_PHOTO_PUT_BLOCK;
5656

5757
static Imaging
5858
ImagingFind(const char *name) {
59-
Py_ssize_t id;
59+
PyObject *capsule;
60+
size_t name_len = strlen(name);
61+
const char *expected = "<capsule object \"" IMAGING_MAGIC "\" at 0x";
6062

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

71-
return (Imaging)id;
77+
return (Imaging)PyCapsule_GetPointer(capsule, IMAGING_MAGIC);
7278
}
7379

7480
static int

0 commit comments

Comments
 (0)