示例工程 25-c-extensions-ctypes-cffi
25-c-extensions-ctypes-cffi/01-ctypes-libc/ctypes_libc.py
"""用 ctypes 调用 libc 的 strlen(无需编译扩展)。"""
from __future__ import annotations
import ctypes
import ctypes.util
def load_libc() -> ctypes.CDLL:
name = ctypes.util.find_library("c")
return ctypes.CDLL(name) if name else ctypes.CDLL(None)
def c_strlen(text: str) -> int:
libc = load_libc()
libc.strlen.argtypes = [ctypes.c_char_p]
libc.strlen.restype = ctypes.c_size_t
return int(libc.strlen(text.encode("utf-8")))
def main() -> None:
print(f"strlen('hello'): {c_strlen('hello')}")
print(f"strlen('你好'): {c_strlen('你好')}")
if __name__ == "__main__":
main()