# PyCBinder **Repository Path**: bili_zero123/py-cbinder ## Basic Information - **Project Name**: PyCBinder - **Description**: 基于标准库ctypes实现的简易cpp绑定模块 - **Primary Language**: C++ - **License**: BSD-3-Clause - **Default Branch**: main - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 2 - **Forks**: 0 - **Created**: 2025-02-03 - **Last Updated**: 2025-02-12 ## Categories & Tags **Categories**: Uncategorized **Tags**: Python, Cpp ## README # PyCBinder ### 功能介绍 PyCBinder 是一个基于标准库 `ctypes` 实现的简易 C++ 绑定模块。只需在 Python 中定义目标函数,即可自动绑定并关联到目标 C/C++ 函数。 ### 基本实现 通过装饰器机制重新定向函数调用逻辑,直接关联目标实现。对于静态数据类型(如 `int`、`float` 等),将直接调用并返回。对于动态数据类型(如 `const char*` 字符串),则通过回调函数返回数据,避免动态内存分配带来的内存泄漏隐患。 ### 示例代码 ```python from QNative.CLoader import CLibBinder, C_CastType # 绑定动态链接库 test = CLibBinder("Libs/QTestLib/out/build/x64-release/QTestLib.dll") # 在py层定义函数并转发到动态库调用 @test.native(returnType=C_CastType.cFloat) def getSysTime(): return 0.0 @test.native(returnType=C_CastType.cString) def getLevelName(): return "" @test.native([C_CastType.cString], C_CastType.cBool) def hasEntity(entityId): return False @test.native([C_CastType.cStringArray], C_CastType.cStringArray, bindfuncName="sorted") def cppSorted(strList): return [""] @test.native([C_CastType.cString], C_CastType.cJson) def getEntityNBT(entityId): return {} # py3.7+ 形参类型自动绑定 @test.py3AutoBinder def sumTo(start: int, to: int, length: int) -> int: return 0 @test.py3AutoBinder def getSystemSoundVolume() -> int: return 0 @test.py3AutoBinder def setSystemSoundVolume(a: int): pass ``` ### 已知缺点 - 完全依赖 Python 运行时类型检查及转换 - 跨语言的调用开销较高 在高频调用下性能远不如 CPython API - 仅供娱乐使用