[swift-users] Using withUnsafePointer on char arrays within C structs

Russell Finn rsfinn at gmail.com
Wed Feb 22 16:16:13 CST 2017


Greetings — I haven't found this specific topic in the archives; apologies
if this has come up before.

Suppose I have a C struct with an embedded char array:

struct fileinfo_t {
    char path[256];
};

and I want to convert the path to a Swift String (in order to implement
`description`, say).  I would like to use String.init(cString:) for this;
but the `path` field is imported as a tuple of 256 `Int8`s, and I need to
get an `UnsafePointer<CChar>`.

So I would like to write something like this:

extension fileinfo_t: CustomStringConvertible {
    public var description: String {
        let path = withUnsafePointer(to: &self.path) {
            $0.withMemoryRebound(to: CChar.self, capacity:
MemoryLayout.size(ofValue: self.path) {
                $0
            }
        }
        return "fileinfo_t: \(path)"
    }
}

The problem is that `self.path` is immutable, so I can't pass it to the
inout parameter of `withUnsafePointer(to:)`, even though its value is never
modified.  I can either (1) write the `description` accessor as `mutating
get` — but then it no longer conforms to `CustomStringConvertible` — or (2)
copy the `path` field into a local `var` that can be passed to
`withUnsafePointer(to:)`, and hope that the compiler can optimize away the
copy.

In the absence of the Swift 4 ownership model (with which I presume this
could be marked as a borrowed reference), is (2) the best I can do for
now?  And is this the sort of issue that the Ownership Manifesto is
designed to address?

Thanks,

— Russell Finn
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170222/314fd8fb/attachment.html>


More information about the swift-users mailing list