Swift-Linux-Glibc: error: cannot find type 'DIR' in scope

Trying to play with Swift port on Linux (Docker-Fedora) I encounter a missing type 'name' in scope.

#if os(Linux)
    import Glibc
    import Darwin

let path = "/usr/local/"

let dir: UnsafeMutablePointer<DIR>?
dir = opendir(path)

I get an error:

main.swift:22:31: error: cannot find type 'DIR' in scope
let dir: UnsafeMutablePointer<DIR>?

Let say it works perfectly on Darwing and that the type if plainly part of Glibc/dirent.h

If I let swift compiler to infer the type I don't get an issue:

let dir = opendir(path)

I wrote the equiv in C on the same config and didn't get any issue.


int main() {
    char* path = "/usr/local/";
    DIR *dir = opendir(path);

Any adea?

This is an unfortunate manifestation of the issues discussed in Opaque Pointers in Swift.

The specific problem you're hitting is that in glibc the DIR type is opaque: that is, the C header file does not express the layout of the type, only that it exists. In C this has no particular impact at the type level, you just can't dereference the pointer or stack-allocate a value of it. In Swift, however, it entirely changes the type. The reason you're hitting this is that the type is not opaque on Darwin.

In general Swift does not attempt to keep libc types the same across systems (which is good, as it'd be an impossible task). For you, you can either use a typealias to specify the type for each system, or you can convert to OpaquePointer and back on all systems.

Thanks Lukasa.
I saw it was an OpaquePointer? but I didn't think at first I could just try to convert it to that.
I'll try that: typealias it or convert to OpaquePointer.

Alternatively, you could use FileManager for this. While Foundation isn’t perfect on non-Apple platforms, it’s more than capable of iterating a directory (-:

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

:-) Sure

Terms of Service

Privacy Policy

Cookie Policy