简体   繁体   中英

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 :

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;

I'm trying to achieve same thing with Swift, I tried:

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. What would be closest Swift implementation of mentioned C struct? And no, it's not premature optimisation.

The equivalent to the C struct would look like

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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