Metadata-Version: 2.4
Name: pycstructdataparser-lib
Version: 1.0.0
Summary: Parse C/C++ struct definitions from header text and serialize/deserialize binary data with ctypes — no compilation needed
Author: NGC13009
License-Expression: GPL-3.0-only
Project-URL: Homepage, https://github.com/NGC13009/cStructDataParser
Project-URL: Source, https://github.com/NGC13009/cStructDataParser
Project-URL: Tracker, https://github.com/NGC13009/cStructDataParser/issues
Keywords: ctypes,C struct,binary,serialization,deserialization,header parser,pack,unpack,c-struct,binary-parser,embedded,protocol,pragma-pack,bitfield,struct-parser
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Archiving :: Packaging
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# cStructDataParser

<p align="center">
  <a href="https://pypi.org/project/pycstructdataparser-lib/"><img src="https://img.shields.io/pypi/v/pycstructdataparser-lib" alt="PyPI"></a>
  <a href="https://pypi.org/project/pycstructdataparser-lib/"><img src="https://img.shields.io/pypi/pyversions/pycstructdataparser-lib" alt="Python Versions"></a>
  <a href="LICENSE"><img src="https://img.shields.io/badge/License-GPLv3-blue.svg" alt="License: GPL v3"></a>
</p>

---

> **直接从 C/C++ 头文件文本解析结构体定义并处理二进制数据** —— 无需编译，无需手动编写 `ctypes.Structure` 子类，零模板代码。

---

## 概述

使用 Python 的 `ctypes` 模块解析 C/C++ 结构体定义对应的二进制数据。你只需提供头文件中的结构体定义文本，即可完成二进制数据的序列化（pack）与反序列化（unpack）。

## 痛点解决

传统方式处理 C 结构体二进制数据，通常需要：

- 手动计算偏移量，使用 `struct.pack/unpack`
- 手动编写 `ctypes.Structure` 子类
- 借助第三方编译工具生成绑定代码

**cStructDataParser 让你直接从 C 头文件文本解析，一步到位。**

## 特性

- **C 头文件解析**：解析 C/C++ 头文件中的 `typedef struct { … } TypeName;` 代码块
- **`#pragma pack` 支持**：正确处理 `#pragma pack(push, N)` 和 `#pragma pack(pop)` 栈
- **位域支持**：解析类似 `unsigned char field : 2;` 的位域声明
- **数组支持**：处理固定大小数组，例如 `Type array[10];`
- **嵌套结构体**：支持嵌套的具名结构体类型
- **二进制序列化**：`pack()` —— 将 Python 字典转换为 C 结构体的二进制字节
- **二进制反序列化**：`unpack()` —— 将原始字节解析回 Python 字典
- **严格模式**：在打包时，可选地验证所有非位域键是否存在

## 安装

```bash
pip install pycstructdataparser-lib
```

或者将源文件（`cstruct_parser.py`、`ctype_map_def.py`、`pycstructdataparser_lib.py`）直接复制到你的项目中。

## 快速开始

```python
from pycstructdataparser_lib import CStructParser, pack, unpack

header = '''
#pragma pack(push, 1)
typedef struct {
    unsigned char id;
    unsigned int  value;
    float         data[4];
} MyStruct;
#pragma pack(pop)
'''

# 解析头文件
parser = CStructParser()
parser.parse(header)

# 将字典打包为二进制
original = {'id': 10, 'value': 12345, 'data': [1.0, 2.0, 3.0, 4.0]}
raw = pack(parser, 'MyStruct', original)
print(f"二进制大小：{len(raw)} 字节")   # 输出: 21 字节

# 将二进制解包回字典
restored = unpack(parser, 'MyStruct', raw)
print(restored)
# 输出: {'id': 10, 'value': 12345, 'data': [1.0, 2.0, 3.0, 4.0]}
```

## 为什么选择 cStructDataParser？

| 场景 | 传统做法 | 本库做法 |
|------|---------|---------|
| 有一个 C 头文件，想直接解析二进制 | 手工分析结构体布局 → `struct.pack/unpack` 或手写 `ctypes.Structure` | **直接传入头文件文本，一行代码完成解析** |
| 结构体包含 `#pragma pack` | 手动核对对齐值，容易出错 | **自动解析，零配置** |
| 结构体包含位域 | `struct` 模块不支持，需手算位偏移 | **原生支持 `field: N` 语法** |
| 结构体包含嵌套、数组 | 手动递归处理 | **自动递归解析** |

## 对比生态

|  | `struct` 模块 | `ctypes.Structure` | `construct` 库 | **cStructDataParser** |
|--|:---:|:---:|:---:|:---:|
| 从头文件文本直接解析 | ❌ | ❌ | ❌ | ✅ |
| `#pragma pack` 自动对齐 | ❌ | ❌ | ❌ | ✅ |
| 位域支持 | ❌ | ✅ | ✅ | ✅ |
| 嵌套结构体 | 手动 | 手动 | ✅ | ✅ |
| 零模板代码 | ❌ | ❌ | ❌ | ✅ |
| 纯 Python / 无外部依赖 | ✅ | ✅ | ✅ | ✅ |

## API 参考

### `CStructParser`

| 方法 | 描述 |
|------|------|
| `parse(header_content)` | 解析 C/C++ 头文件字符串，并注册结构体类型。 |
| `get_struct_class(name)` | 返回指定类型名称对应的 `ctypes.Structure` 子类。 |
| `struct_classes` (属性) | 返回所有已注册结构体类的字典。 |

### `pack(parser, struct_name, data_dict, strict=True)`

将 Python 字典序列化为 C 结构体的二进制字节。

- `strict=True`（默认值）：如果缺少任何非位域键，则引发 `ValueError`。
- `strict=False`：静默地将缺失的键默认设置为 0。

### `unpack(parser, struct_name, data)`

将原始字节反序列化为嵌套的 Python 字典。

## 支持的 C 类型

| C 类型 | ctypes 类型 |
|--------|-------------|
| `char`, `signed char` | `c_byte` |
| `unsigned char` | `c_ubyte` |
| `short`, `short int` | `c_short` |
| `unsigned short` | `c_ushort` |
| `int`, `signed int` | `c_int` |
| `unsigned int` | `c_uint` |
| `long`, `long int` | `c_long` |
| `unsigned long` | `c_ulong` |
| `long long`, `long long int` | `c_longlong` |
| `unsigned long long` | `c_ulonglong` |
| `float` | `c_float` |
| `double` | `c_double` |
| `long double` | `c_longdouble` |
| `int8_t` .. `uint64_t` | `c_int8` .. `c_uint64` |
| `float32_t` | `c_float` |
| `float64_t` | `c_double` |

## 许可证

本项目基于 GNU 通用公共许可证 v3.0 授权.
