Search code examples
pythonswiftxcodexcodebuildswift-package-manager

How can I use a swift package in python?


I am trying to interface Swift functions to Python. Python can interpret any @_cdecl functions in a .dylib.

For a project directory with a single Swift source:

project/
    test.swift
    test.py

I can run swiftc test.swift -emit-library to generate a .dylib file.

More advanced, using a Swift Package, it looks like this:

project/
    TestPackage/
        ...
    test.py

In my Swift Package, I can pass the -emit-library parameter to the Swift Compiler within swift build like such: swift build -Xswiftc -emit-library. This exports my package to a .dylib.

My problem is adding dependencies to my package. I added the SwifterSwift package as a dependency just to test, and ran swift build -Xswiftc -emit-library. I got this error:

swift build -Xswiftc -emit-library
Undefined symbols for architecture x86_64:
  "_$s10Foundation4DateV12SwifterSwiftE11weekOfMonthSivg", referenced from:
      _$s11TestPackage6swiftyyyF in TestPackage.swift.o
ld: symbol(s) not found for architecture x86_64
<unknown>:0: error: link command failed with exit code 1 (use -v to see invocation)

However, it looks like SwifterSwift exported a .dylib successfully. But my main project, TestPackage did not. swift build did work on its own, but does not reach my goal for generating a .dylib.

Question:

How can I get the whole package to compile as .dylib with dependencies? Am I missing a linker command?


Solution

  • After hours of experimenting with swift build and swiftc variations, I found the much easier solution:

    In the manifest, set type to dynamic.

    .library(name: "TestPackage", type: .dynamic, targets: ["TestPackage"]),

    After swift build (no fancy parameters), the .dylib is found at:

    TestPackage/.build/x86_64-apple-macosx/debug/libTestPackage.dylib

    Now I can use some Swift Packages in Python!