# Dynamically loading a Swift \`shared object\` / \`dylib\`

**URL:** <https://forums.swift.org/t/dynamically-loading-a-swift-shared-object-dylib/62732>\
**Category:** Using Swift\
**Created:** [January 22, 2023, 4:24pm UTC](https://forums.swift.org/t/dynamically-loading-a-swift-shared-object-dylib/62732 "2023-01-22T16:24:15Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![stuchlej](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/stuchlej/32/7751_2.png) [@stuchlej](https://forums.swift.org/u/stuchlej)\
**Post date:** [January 22, 2023, 4:24pm UTC](https://forums.swift.org/t/dynamically-loading-a-swift-shared-object-dylib/62732/1 "2023-01-22T16:24:15Z")

</div>

Hello,

I have a Swift code, that loads a Swift `.dylib` (or `.so`) at runtime and uses a function of of a known name type as an interface. The loading process then uses `dlopen` and `dlsym` to execute the function. (I do not )

The source code of `.dylib`

```swift
@_cdecl("mySymbol")
public func mySymbol() -> Any {
    return "Hello world!"
}

```

The source code of the application

```swift
typealias FunctionPrototype = @convention(c) () -> Any

let handle = dlopen(libraryPath, RTLD_NOW)!
let symbol = dlsym(handle, "mySymbol")
let callable = unsafeBitCast(symbol, to: FunctionPrototype.self)
print(callable() as! String)

```

Everything works fine and I have never had an issue.

However, I was wondering, whether there might be an issue with calling conventions, since I'm using the `@convention(c)` annotation. I've used it "to make the `FunctionPrototype` type 1 pointer wide", but are there any other effects caused by the annotation, that I'm not taking into consideration? Is there any standard type, that might just break the program?

---

<div class="post-metadata">

**Author:** ![Alejandro](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/alejandro/32/46197_2.png) [@Alejandro](https://forums.swift.org/u/Alejandro)\
**Post date:** [January 22, 2023, 10:07pm UTC](https://forums.swift.org/t/dynamically-loading-a-swift-shared-object-dylib/62732/2 "2023-01-22T22:07:09Z")

</div>

Marking the function as `@_cdecl` forces it to use the c calling convention, so what you're doing looks fine to me.

> [@stuchlej](#):
>
> Is there any standard type, that might just break the program?

Types that aren't compatible with the c calling convention should be diagnosed by the compiler on both/either the actual function definition because it's marked `@_cdecl` or the function type.
