简体   繁体   English

如何从 Octave 或 Matlab 中的文件加载 C 结构

[英]How to load a C struct from a file in Octave or Matlab

I have an array of C struct's like我有一个 C 结构的数组,比如

typedef struct{
    uint32_t timestamp;
    uint16_t channels[4];
    float    value;
} sample_t;

Which is write to a file with something like这是用类似的东西写入文件

fwrite(&sample,sizeof(sample_t),1,fpLog)

What's a good way to load this into a array of struct in Octave/Matlab?将它加载到 Octave/Matlab 中的结构数组中的好方法是什么?

Edit: The goal is optimization for speed.编辑:目标是优化速度。 The files are 1GB+ big and take a very long time to load in matlab.这些文件有 1GB+ 大,在 matlab 中加载需要很长时间。 The files load 100x faster in numpy.文件在 numpy 中的加载速度提高了 100 倍。

There is aligned rules for each C/C++ struct/class. 每个C / C ++结构/类都有统一的规则。 See for example Eric Postpischil's answer in How is the size of a C++ class determined? 例如, 如何确定C ++类的大小,请参阅Eric Postpischil的答案 . Very imported citate: 非常进口的柠檬酸盐:

For elementary types (int, double, et cetera), the alignment requirements are implementation dependent and are largely determined by the hardware. 对于基本类型(int,double等),对齐要求取决于实现方式,并且在很大程度上取决于硬件。

So aligned rules for C/C++ compiler and Matlab/Octave can be different. 因此,C / C ++编译器和Matlab / Octave的对齐规则可能不同。 You can solve yore problem: 您可以解决以往的问题:

  1. Write data to file by components: 按组件将数据写入文件:

     fwrite(&sample.timestamp,sizeof(sample.timestamp),1,fpLog) fwrite(sample.channels,sizeof(sample.channels[0]),sizeof(sample.channels)/sizof(sample.channels[0]),fpLog) fwrite(&sample.value,sizeof(sample.value),1,fpLog) 
  2. Read file in Matlab/Octave by componets too: 也可以通过组件在Matlab / Octave中读取文件:

     ts = fread(fplog,"uint32"); sample.timestamp = ts; ch = fread(fplog,"uint16",4); sample.channels = ch; vl = fread(fplog,"float32"); sample.value = vl; sample 

Do not forget to open files in binary mode!!! 不要忘记以二进制模式打开文件!!!

A trick : one can generate the .m I/O statements by parsing the C-struct definition with the GDB Python API .一个技巧:可以通过使用GDB Python API解析 C 结构定义来生成 .m I/O 语句。 When the binary file to read is produced by an ELF/object/executable and you have a Debug (gcc -g) version of it.当要读取的二进制文件由 ELF/对象/可执行文件生成并且您拥有它的调试 (gcc -g) 版本时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM