Files
TransPyC/Test/StructTest/App/main.py
2026-06-16 16:09:42 +08:00

101 lines
2.9 KiB
Python

import t
import stdio
import string
# 定义结构体
class Point(t.Struct):
x: t.CInt
y: t.CInt
class Rect(t.Struct):
origin: Point
size: Point
class Node(t.Struct):
value: t.CInt
next: t.CPtr | t.CVoid # Node* 类型
def test_struct_basic():
stdio.printf("--- Test 1: struct basic ---\n")
p: Point = Point()
p.x = 10
p.y = 20
if p.x == 10 and p.y == 20:
stdio.printf("PASS: struct basic (x=%d y=%d)\n", p.x, p.y)
else:
stdio.printf("FAIL: struct basic (x=%d y=%d, expect 10 20)\n", p.x, p.y)
def test_struct_nested():
stdio.printf("--- Test 2: struct nested ---\n")
r: Rect = Rect()
r.origin.x = 1
r.origin.y = 2
r.size.x = 100
r.size.y = 200
if r.origin.x == 1 and r.origin.y == 2 and r.size.x == 100 and r.size.y == 200:
stdio.printf("PASS: struct nested (origin=%d,%d size=%d,%d)\n", r.origin.x, r.origin.y, r.size.x, r.size.y)
else:
stdio.printf("FAIL: struct nested\n")
def test_struct_pointer():
stdio.printf("--- Test 3: struct pointer ---\n")
p: Point = Point()
p.x = 42
p.y = 84
# 取结构体指针
pp: Point | t.CPtr = t.CPtr(t.CVoid(t.CUInt64T(p), t.CPtr))
# 通过指针修改
pp.x = 100
pp.y = 200
# 检查原始结构体是否被修改
if p.x == 100 and p.y == 200:
stdio.printf("PASS: struct pointer (x=%d y=%d)\n", p.x, p.y)
else:
stdio.printf("FAIL: struct pointer (x=%d y=%d, expect 100 200)\n", p.x, p.y)
def test_struct_param():
stdio.printf("--- Test 4: struct as parameter ---\n")
p: Point = Point()
p.x = 5
p.y = 15
sum_val: t.CInt = point_sum(p)
if sum_val == 20:
stdio.printf("PASS: struct param (sum=%d)\n", sum_val)
else:
stdio.printf("FAIL: struct param (sum=%d, expect 20)\n", sum_val)
def point_sum(p: Point) -> t.CInt:
return p.x + p.y
def test_struct_array():
stdio.printf("--- Test 5: struct array ---\n")
# 分配结构体数组
buf: t.CUInt8T | t.CPtr = w32.win32memory.VirtualAlloc(t.CVoid(0, t.CPtr), 256, 12288, 4)
if t.CUInt64T(buf) == 0:
stdio.printf("SKIP: VirtualAlloc returned NULL\n")
return
string.memset(buf, 0, 256)
# 将缓冲区转为 Point 数组
pts: Point | t.CPtr = (Point | t.CPtr)(t.CVoid(t.CUInt64T(buf), t.CPtr))
pts[0].x = 1
pts[0].y = 2
pts[1].x = 3
pts[1].y = 4
total: t.CInt = pts[0].x + pts[0].y + pts[1].x + pts[1].y
if total == 10:
stdio.printf("PASS: struct array (total=%d)\n", total)
else:
stdio.printf("FAIL: struct array (total=%d, expect 10)\n", total)
import w32.win32memory
def main() -> t.CInt:
stdio.printf("=== StructTest: 结构体操作基准测试 ===\n\n")
test_struct_basic()
test_struct_nested()
test_struct_pointer()
test_struct_param()
test_struct_array()
stdio.printf("\n=== StructTest Complete ===\n")
return 0