简体   繁体   English

Swift 中的 C 结构表示

[英]C struct representation in Swift

Think in C: I have memory buffer (flat 3D) with millions of Object structs and I want to have re-calculated neighbours :用 C 语言思考:我有包含数百万个Object结构的内存缓冲区(平面 3D),我想重新计算邻居:

typedef struct Object {
    vector_int3 coords;
    struct Object *neighbours[6]; // Neighbouring objects in 6 directions
    int prop1;
} Object;

to be able later access for example chunk->neighbours[TOP]->prop1;能够稍后访问例如chunk->neighbours[TOP]->prop1;

I'm trying to achieve same thing with Swift, I tried:我试图用 Swift 实现同样的事情,我试过:

struct Object {
    var coords: vector_int3
    // IMO this is wrong, because it allocates new heap buffer for 6 pointers
    var neighbours = UnsafeMutablePointer<Chunk>.allocate(capacity: 6)
    var prop1: Int
    ...
}

I just want to have buffer of 6 pointers to Object in Swift to be able to access it by index.我只想在 Swift 中拥有 6 个指向Object指针的缓冲区,以便能够通过索引访问它。 What would be closest Swift implementation of mentioned C struct?提到的 C 结构最接近的 Swift 实现是什么? And no, it's not premature optimisation.不,这不是过早的优化。

The equivalent to the C struct would look like相当于 C 结构的看起来像

struct Object {
    var coords: vector_int3
    var neighbours: (UnsafeMutablePointer<Chunk>, UnsafeMutablePointer<Chunk>, UnsafeMutablePointer<Chunk>, UnsafeMutablePointer<Chunk>, UnsafeMutablePointer<Chunk>, UnsafeMutablePointer<Chunk>)
    var prop1: Int
    ...
}

And yes, it's quite unwieldy.是的,它非常笨拙。

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

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