簡體   English   中英

Swift 中的 C 結構表示

[英]C struct representation in Swift

用 C 語言思考:我有包含數百萬個Object結構的內存緩沖區(平面 3D),我想重新計算鄰居:

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

能夠稍后訪問例如chunk->neighbours[TOP]->prop1;

我試圖用 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
    ...
}

我只想在 Swift 中擁有 6 個指向Object指針的緩沖區,以便能夠通過索引訪問它。 提到的 C 結構最接近的 Swift 實現是什么? 不,這不是過早的優化。

相當於 C 結構的看起來像

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

是的,它非常笨拙。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM