[英]What is an efficient way to compile untyped arrays to C?
I'm compiling code from a language that allows for untyped, dynamic arrays (such as JavaScript) to C. What is the best way to represent those arrays on it? 我正在从允许将无类型的动态数组(例如JavaScript)转换为C的语言来编译代码。在其上表示这些数组的最佳方法是什么? Example:
例:
var array = [1,2,"test",[1,2]];
array.push([5]);
Notice the lack of proper shape and size. 请注意缺少适当的形状和大小。
For the lack of proper shape, I've thought in boxing everything in a struct, that would contain a pointer to the actual objects. 由于缺乏适当的形状,我考虑过将结构中的所有内容装箱,其中会包含指向实际对象的指针。 So I could have an array of that box.
所以我可以有一个盒子的数组。 Would GCC be capable of unboxing that so I have no performance penalties, or should I look for an alternative solution?
GCC是否可以取消装箱,所以我没有性能损失,还是应该寻找替代解决方案?
For the lack of static size, I'm not sure what the best approach is. 由于缺少静态大小,因此我不确定最佳方法是什么。
This is generally what unions are for; 这通常是工会的目的。 at least, they're the most memory- and time-efficient solution.
至少,它们是最节省内存和时间的解决方案。 Make each entry of the array a struct with two members: an integer that marks the type of data, and a union containing all possible types you might store.
使数组的每个条目成为具有两个成员的结构:一个用于标记数据类型的整数,一个包含您可能存储的所有可能类型的联合。
Example: 例:
struct typed_elem {
int type;
union {
int32_t i;
double f;
char *s;
struct typed_elem *a;
} value;
};
This would allow your array to contain integers, floating point (doubles), strings, or further arrays like itself. 这将允许您的数组包含整数,浮点(双精度),字符串或其他类似数组。 The
type
member would hold a code (you may prefer to use enum
instead of int
) you make up to tell your program which member of the union is active. type
成员将持有一个代码(您可能希望使用enum
而不是int
)来弥补程序告诉程序中哪个联合成员处于活动状态。
You should either use ArrayBuffer (TypedArrays / ByteArrays) in Javascript to create structs that are static or transmit data via JSON between the two languages. 您应该在Javascript中使用ArrayBuffer(TypedArrays / ByteArrays)创建静态结构,或者通过JSON在两种语言之间传输数据。 In order to use dynamic structures in C, you will need to come up with some form of a header for each element that will give you a clue on how to parse the next few bits.
为了在C语言中使用动态结构,您将需要为每个元素提供某种形式的头,这将为您提供有关如何解析下几位的线索。
What I would suggest is to use Typed Arrays . 我建议使用Typed Arrays 。 That way you can have an identical struct in C and Javascript.
这样,您就可以在C和Javascript中使用相同的结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.