1

I'm dynamically loading symbols from a dynamic library. However there is one problem - I have to manually provide the types of symbols. I have a C header with the global variables and functions, however it's useful only when linking statically or without dynamically loading the symbols. I was thinking I could leverage the header somehow and view it as converted to Swift or even better - use the types there without much manual work.

To illustrate here is a sample C header:

uint32_t foo;
uint32_t bar(const void* x);

Here's what I would have in Swift:

class Lib {
    let myFoo: UnsafeMutablePointer<UInt32>?
    typealias cFuncBar = @convention(c) (UnsafeRawPointer) -> UInt32
    let myBar: cFuncBar?

    init(withHandle handle: UnsafeMutableRawPointer) {
        myFoo = dlsym(handle, "foo")
        myBar = dlsym(handle, "bar")
    }
}

I tried using type(of:) like so:

    let myFoo: UnsafeMutablePointer<type(of: foo)>?
    let myBar: type(of: bar)?

however there were syntax errors.

I also tried .dynamicType:

    let myFoo: UnsafeMutablePointer<foo.dynamicType>?
    let myBar: bar.dynamicType?

but this time there is a compile error that it can't find foo and bar in scope (despite otherwise managing to find them just fine).

To clarify, I'm not looking for a way to invoke the imported symbols. I'm just looking for a way to have the types be matched to the header automatically, or to at least view the C header as converted to Swift.

Jo3Jo
  • 21
  • 6
  • See https://gist.github.com/neonichu/dcf49b26a2742404d8f1 You probably need `unsafeBitCast` to do the trick here. – Sweeper Oct 03 '22 at 18:11
  • Possibly helpful: https://stackoverflow.com/a/34670401/1187415 – Martin R Oct 03 '22 at 18:13
  • @Sweeper I think it's outdated as I didn't have to do any `unsafeBitCast`. Also the part of calling the functions is resolved, I'm just looking for a way to automate assigning the types to them. – Jo3Jo Oct 03 '22 at 18:44
  • @MartinR Oh, I didn't know that typedefs are imported too, however I'd be more happy if I could get the types without having the typedefs. Again though, I'm not asking how to call a dynamic library function, that part I have already resolved. – Jo3Jo Oct 03 '22 at 18:48
  • That is not possible, as far as I know. – Martin R Oct 03 '22 at 19:27

0 Answers0