Last active
March 15, 2017 15:56
-
-
Save lebedov/81343ac4e5867d6668103d1e322cbff1 to your computer and use it in GitHub Desktop.
Simple demo of how to write structs from C and read them in Python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
write: write.c | |
gcc $< -o $@ | |
test: write | |
./write | |
python read.py |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from construct import Struct, Int32un, Float32n | |
print '--- not nested ---' | |
x = Struct('c' / Int32un, 'x' / Float32n) | |
with open('out.raw', 'rb') as f: | |
result = [] | |
while True: | |
buf = f.read(x.sizeof()) | |
if len(buf) != x.sizeof(): | |
break | |
result.append(x.parse(buf)) | |
print result | |
print '--- nested ---' | |
y = Struct('a' / Int32un, 's' / x) | |
with open('out_nested.raw', 'rb') as f: | |
result = [] | |
while True: | |
buf = f.read(y.sizeof()) | |
if len(buf) != y.sizeof(): | |
break | |
result.append(y.parse(buf)) | |
print result |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
typedef struct MyStruct { | |
int c; | |
float x; | |
} MyStruct_t; | |
typedef struct MyStructNested { | |
int a; | |
MyStruct_t s; | |
} MyStructNested_t; | |
int main(void) { | |
int n = 3; | |
MyStruct_t m[n]; | |
m[0].c = 1; m[0].x = 3.5; | |
m[1].c = 2; m[1].x = 7.2; | |
m[2].c = 3; m[2].x = 1.9; | |
FILE * f = fopen("out.raw", "wb"); | |
for (int i = 0; i < n; i++) { | |
fwrite(&m[i], sizeof(MyStruct_t), 1, f); | |
} | |
fclose(f); | |
MyStructNested_t mn[n]; | |
mn[0].a = 1; | |
mn[0].s.c = 2; | |
mn[0].s.x = 3.5; | |
mn[1].a = 2; | |
mn[1].s.c = 4; | |
mn[1].s.x = 1.7; | |
mn[2].a = 3; | |
mn[2].s.c = 0; | |
mn[2].s.x = 2.9; | |
f = fopen("out_nested.raw", "wb"); | |
for (int i = 0; i < n; i++) { | |
fwrite(&mn[i], sizeof(MyStructNested_t), 1, f); | |
} | |
fclose(f); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment