如何通过ctypes将胶囊的名称传入PyCapsule_New的第二个参数
我尝试过以下方法,但似乎有问题:
capsule = ctypes.pythonapi.PyCapsule_New(b'data', b'abcdef.ghijkl', None)
capsule = ctypes.pythonapi.PyCapsule_New(b'data', ctypes.create_string_buffer(b"abcdef.ghijkl"), None)
capsule = ctypes.pythonapi.PyCapsule_New(b'data', ctypes.c_chap_p(b"abcdef.ghijkl"), None)例如,胶囊的名称设置不正确:
>>> import ctypes
>>> ctypes.pythonapi.PyCapsule_New.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_void_p]
>>> ctypes.pythonapi.PyCapsule_New.restype = ctypes.py_object
>>>
>>> capsule = ctypes.pythonapi.PyCapsule_New(b'data', b'abcdef.ghijkl', None)
>>>
>>> capsule
<capsule object "" at 0xf7102f98>
>>> capsule
<capsule object "e" at 0xf7102f98>
>>> capsule
<capsule object "���capsule
<capsule object "" at 0xf7102f98>
>>> capsule
<capsule object "e" at 0xf7102f98>
>>> capsule
<capsule object "e" at 0xf7102f98>
>>> capsule
<capsule object "���如果我使用ctypes.create_string_buffer(b"abcdef.ghijkl")
>>> capsule = ctypes.pythonapi.PyCapsule_New(b'data', ctypes.create_string_buffer(b"abcdef.ghijkl"), None)
>>> capsule
<capsule object "abcdef.ghijkl" at 0xf7102fb0>
>>> capsule
<capsule object "" at 0xf7102fb0>
>>> capsule
<capsule object "" at 0xf7102fb0>
>>> capsule
<capsule object "" at 0xf7102fb0>
>>> capsule
<capsule object "" at 0xf7102fb0>这里奇怪的是,如果我做了一个返回胶囊的C扩展,我可以使用ctype提取它的名称,并且它可以工作:
>>> capsule_from_c_ext = mycext.capsule()
>>> ctypes.pythonapi.PyCapsule_GetName.restype = ctypes.c_char_p
>>> ctypes.pythonapi.PyCapsule_GetName.argtypes = [ctypes.py_object]
>>> name = ctypes.pythonapi.PyCapsule_GetName(capsule_from_c_ext)
>>> name
b"abcdef.ghijkl"
>>> type(name)
<class 'bytes'>
>>> assert name == b"abcdef.ghijkl"
>>>
>>> capsule = ctypes.pythonapi.PyCapsule_New(b'data', name, None)
>>> capsule
<capsule object "abcdef.ghijkl" at 0xf6f23c20>
>>> capsule
<capsule object "abcdef.ghijkl" at 0xf6f23c20>
>>> capsule
<capsule object "abcdef.ghijkl" at 0xf6f23c20>
>>>
>>> capsule
<capsule object "abcdef.ghijkl" at 0xf6f23c20>
>>> capsule
<capsule object "abcdef.ghijkl" at 0xf6f23c20>此外,如果您使用一个较短的名称,如b'name',它似乎可以正常工作。
发布于 2020-02-21 08:15:10
我从docs得到了一个提示
名称字符串可以是NULL,也可以是指向有效C字符串的指针。如果不为空,此字符串的存留时间必须大于胶囊。(尽管允许它在析构函数中释放它。)
首先创建一个名为的变量,然后调用它,似乎是可行的:
>>> import ctypes
>>> ctypes.pythonapi.PyCapsule_New.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_void_p]
>>> ctypes.pythonapi.PyCapsule_New.restype = ctypes.py_object
>>> name = b'abcdef.ghijkl'
>>> capsule = ctypes.pythonapi.PyCapsule_New(b'data', name, None)
>>>
>>> capsule
<capsule object "abcdef.ghijkl" at 0xf6f23bd8>
>>> capsule
<capsule object "abcdef.ghijkl" at 0xf6f23bd8>
>>> capsule
<capsule object "abcdef.ghijkl" at 0xf6f23bd8>
>>> capsule
<capsule object "abcdef.ghijkl" at 0xf6f23bd8>并且您可以证明您需要name变量不被释放:
del name
>>> capsule
<capsule object "" at 0xf7102fb0>
>>> capsule
<capsule object "" at 0xf7102fb0>
>>> capsule
<capsule object "" at 0xf7102fb0>
>>> capsule
<capsule object "" at 0xf7102fb0>https://stackoverflow.com/questions/60330422
复制相似问题