# How do I initialize a C struct from a Data object?

**URL:** <https://forums.swift.org/t/how-do-i-initialize-a-c-struct-from-a-data-object/62323>\
**Category:** Using Swift\
**Tags:** c-interop, pointers\
**Created:** [December 31, 2022, 8:04pm UTC](https://forums.swift.org/t/how-do-i-initialize-a-c-struct-from-a-data-object/62323 "2022-12-31T20:04:24Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![snej](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/snej/32/365_2.png) [@snej](https://forums.swift.org/u/snej)\
**Post date:** [December 31, 2022, 8:04pm UTC](https://forums.swift.org/t/how-do-i-initialize-a-c-struct-from-a-data-object/62323/1 "2022-12-31T20:04:24Z")

</div>

Hi, I’m an expert C/C++ coder, and mostly comfortable in Swift, but I often end up needing to bridge to C APIs, and this always gets me confused and frustrated due to all the all the different unsafe pointer and buffer types and “withUnsafe…” methods.

Today’s saga: All I want to do is initialize a C struct (an array of 32 bytes) from a Swift Data object. _(”All I wanted was a Pepsi! Just one Pepsi! And she wouldn’t give it to me!”)_

I’ve got a C declaration like this:

```c
typedef struct { uint8_t bytes[32]; } SHSPublicKey; ///< A 256-bit Ed25519 public key.

```

It gets mapped to Swift as the rather silly-looking

```swift
public struct SHSPublicKey {

    public init() ///< A 256-bit Ed25519 public key.

    public init(bytes: (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8))

    ///< A 256-bit Ed25519 public key.
    public var bytes: (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8)
}

```

My handmade Swift wrapper is:

```swift
struct PublicKey {
    init?(_ data: Data) {
        guard data.count == MemoryLayout<SHSPublicKey>.size else {return nil}
        _key = SHSPublicKey() # Ugh, compiler forces redundant init
        withUnsafeMutablePointer(to: &_key) { ptr in
            data.copyBytes(to: ptr, count: MemoryLayout<SHSPublicKey>.size) // ERROR
        }
    }

    fileprivate var _key: SHSPublicKey // HACK: Should be `let`
}

```

This fails with: `error: cannot convert value of type 'UnsafeMutablePointer<SHSPublicKey>' to expected argument type 'UnsafeMutablePointer<UInt8>' because instance method 'copyBytes(to:count:)' was not imported from C header` … which makes no sense to me because `copyBytes` is a method of the standard `Data` class, not something from my C header. … Help?

(Also note that Swift forced me to zero-initialize `_key` even though it’s redundant, saying I can’t pass it as `inout` if it’s uninitialized. And `_key` really should be declared as `let` since it’s supposed to be immutable, but if I do that, Swift won’t let me pass it as an inout parameter to initialize it 🤯)

> PS: If there is any good book / article about C interop and pointers, I’d love to know. The Swift book says nothing, the Apple API docs just describe individual methods without showing how to use them, and the blog posts I’ve found are pretty shallow and don’t discuss pointers.

---

<div class="post-metadata">

**Author:** ![snej](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/snej/32/365_2.png) [@snej](https://forums.swift.org/u/snej)\
**Post date:** [December 31, 2022, 8:11pm UTC](https://forums.swift.org/t/how-do-i-initialize-a-c-struct-from-a-data-object/62323/2 "2022-12-31T20:11:52Z")

</div>

I’ve tried fixing the error with a type-cast, `ptr as! UnsafeMutablePointer<UInt8>`, but that produces the warning `warning: cast from 'UnsafeMutablePointer<SHSPublicKey>' to unrelated type 'UnsafeMutablePointer<UInt8>' always fails`.

At this point I’m going to ~~rage-quit Swift~~ go make some calming herbal tea, go to my happy place, and take slow deep breaths.

---

<div class="post-metadata">

**Author:** ![Philippe\_Hausler](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/philippe_hausler/32/22569_2.png) [@Philippe\_Hausler](https://forums.swift.org/u/Philippe_Hausler)\
**Post date:** [December 31, 2022, 8:23pm UTC](https://forums.swift.org/t/how-do-i-initialize-a-c-struct-from-a-data-object/62323/3 "2022-12-31T20:23:04Z")

</div>

One way to accomplish this (since the `SHSPublicKey` type is just a wrapper around a tuple...) is something like this:

```swift
struct PublicKey {
  init?(_ data: Data) {
    guard data.count == MemoryLayout<SHSPublicKey>.size else { return nil }
    _key = data.withUnsafeBytes { buffer in
      buffer.baseAddress!.assumingMemoryBound(to: SHSPublicKey.self).pointee
    }
  }
  
  fileprivate let _key: SHSPublicKey
}

```

---

<div class="post-metadata">

**Author:** ![snej](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/snej/32/365_2.png) [@snej](https://forums.swift.org/u/snej)\
**Post date:** [December 31, 2022, 9:27pm UTC](https://forums.swift.org/t/how-do-i-initialize-a-c-struct-from-a-data-object/62323/4 "2022-12-31T21:27:00Z")

</div>

Thanks! I made a wrapper function so I can reuse it easily:

```swift
fileprivate func fromData<T>(_ data: Data) -> T {
    return data.withUnsafeBytes { buffer in
        buffer.baseAddress!.assumingMemoryBound(to: T.self).pointee
    }
}

```

---

<div class="post-metadata">

**Author:** ![Philippe\_Hausler](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/philippe_hausler/32/22569_2.png) [@Philippe\_Hausler](https://forums.swift.org/u/Philippe_Hausler)\
**Post date:** [January 1, 2023, 12:11am UTC](https://forums.swift.org/t/how-do-i-initialize-a-c-struct-from-a-data-object/62323/5 "2023-01-01T00:11:28Z")

</div>

One word of caution: be careful with that. `T` in those cases must always be bitwise representations - e.g. holding `String` or `[Int]` etc won't do what you might first expect. The `T` must always be a composition of "plain-ol'-data" types e.g. `Int`, `UInt16`, `CChar`, `Float`, tuples containing those types of things, and structs containing those types of things etc.

---

<div class="post-metadata">

**Author:** ![Torust](https://avatars.discourse-cdn.com/v4/letter/t/f17d59/32.png) [@Torust](https://forums.swift.org/u/Torust)\
**Post date:** [January 1, 2023, 12:19am UTC](https://forums.swift.org/t/how-do-i-initialize-a-c-struct-from-a-data-object/62323/6 "2023-01-01T00:19:12Z")

</div>

[`load(as:)`](https://developer.apple.com/documentation/swift/unsaferawbufferpointer/load(frombyteoffset:as:)) is probably a better (or at least more readable) choice than the `buffer.baseAddress!.assumingMemoryBound(to:).pointee` chain; e.g.

```swift
extension SHSPublicKey {
  init?(_ data: Data) {
    guard data.count == MemoryLayout<SHSPublicKey>.size else { return nil }
    self = data.withUnsafeBytes { buffer in
        buffer.load(as: SHSPublicKey.self)
    }
  }
}

```

---

<div class="post-metadata">

**Author:** ![Karl](https://avatars.discourse-cdn.com/v4/letter/k/34f0e0/32.png) [@Karl](https://forums.swift.org/u/Karl)\
**Post date:** [January 1, 2023, 5:12am UTC](https://forums.swift.org/t/how-do-i-initialize-a-c-struct-from-a-data-object/62323/7 "2023-01-01T05:12:45Z")

</div>

+1 for `load`, but I'd actually recommend its cousin, [`loadUnaligned`](https://developer.apple.com/documentation/swift/unsaferawbufferpointer/loadunaligned(frombyteoffset:as:)).

Loading structures directly from packed raw data was one of the [primary motivations](https://github.com/apple/swift-evolution/blob/main/proposals/0349-unaligned-loads-and-stores.md) for adding `loadUnaligned`.
