summaryrefslogtreecommitdiff
path: root/python/examples/dynamic_typing/test.c
diff options
context:
space:
mode:
Diffstat (limited to 'python/examples/dynamic_typing/test.c')
-rw-r--r--python/examples/dynamic_typing/test.c76
1 files changed, 76 insertions, 0 deletions
diff --git a/python/examples/dynamic_typing/test.c b/python/examples/dynamic_typing/test.c
new file mode 100644
index 0000000..86e2229
--- /dev/null
+++ b/python/examples/dynamic_typing/test.c
@@ -0,0 +1,76 @@
+#include <string.h>
+#include <stdio.h>
+#include <dynamic_typing.h>
+
+void pprint_(void *obj, struct type *type) {
+ switch (type->kind) {
+ case TY_BASIC:
+ switch (type->size) {
+ case sizeof(char):
+ printf("(%s)%lu", type->basic, (unsigned long)*(unsigned char *)obj);
+ break;
+ case sizeof(short):
+ printf("(%s)%lu", type->basic, (unsigned long)*(unsigned short *)obj);
+ break;
+ case sizeof(int):
+ printf("(%s)%lu", type->basic, (unsigned long)*(unsigned int *)obj);
+ break;
+ case sizeof(long):
+ printf("(%s)%lu", type->basic, (unsigned long)*(unsigned long *)obj);
+ break;
+ default:
+ printf("?");
+ break;
+ }
+ break;
+ case TY_ARRAY:
+ printf("{ ");
+ void *ptr = obj;
+ for (unsigned long i = 0; i < type->length; i++) {
+ pprint_(obj, type->base);
+ obj += type->base->size;
+ if (i + 1 < type->length) printf(", ");
+ else printf(" ");
+ }
+ printf("}");
+ break;
+ case TY_POINTER:
+ printf("%p[%ld]", *(void **)obj, type->length);
+ break;
+ case TY_FUNCTION:
+ printf("<function>");
+ break;
+ case TY_STRUCT:
+ printf("{ ");
+ for (struct type *member = type->members; member; member = member->next_member) {
+ printf(".%s = ", member->field_name);
+ pprint_((void*)obj + member->offset, member);
+ if (member->next_member) printf(", ");
+ else printf(" ");
+ }
+ printf("}");
+ break;
+ case TY_UNION:
+ printf("<union>");
+ break;
+ }
+}
+
+void pprint(void *obj) {
+ pprint_(obj, dynamic_typeof(obj)->base);
+ printf("\n");
+}
+
+int main() {
+ struct {
+ char x;
+ int y;
+ int z[3];
+ } foo = {1, 2, {3, 4, 5}};
+ pprint(&foo);
+ struct {
+ char a;
+ int b;
+ } bar = {100, 200};
+ pprint(&bar);
+}
generated by cgit on debian on lair
contact matthew@masot.net with questions or feedback