我用命令创建了一个简单的Swift包
cd桌面
mkdir AICore
cd AICore
swift包init --类型库
并将配置编辑为动态库配置,如下所示,
Package.Swift
// swift-tools-version: 5.6
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "AICore",
platforms: [.macOS(.v10_15)],
products: [
.library(name: "AICore", type: .dynamic, targets: ["AICore"]),
],
dependencies: [
],
targets: [
.target(
name: "AICore",
dependencies: [])
]
)
AICore.swift:
import Cocoa
public func launchMyAppKitWindow() {
let app = NSApplication.shared
let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 400, height: 300), styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false)
window.center()
window.title = "My AppKit Window"
window.makeKeyAndOrderFront(nil)
app.run()
}
项目结构:
├── AICore
│ ├── Package.swift
│ ├── README.md
│ └── Sources
│ └── AICore
│ └── AICore.swift
└── Test
├── libAICore.dylib
└── main.py
我已经用swift build编译了我的swift程序,并且我已经将hidden build文件夹在AICore父文件夹中解除隐藏。图书馆位于build->x86_64-apple-macosx->libAICore.dylib
我复制了库并粘贴到测试文件夹,其中有下面的Python脚本进行测试。
import ctypes
# https://docs.python.org/3/library/ctypes.html
# Load the dylib
my_appkit_lib = ctypes.CDLL("/Users/YxT2/Desktop/PY/Test/libAICore.dylib")
# Call the launch function
my_appkit_lib.launchMyAppKitWindow()
我运行的代码使用命令python3 main.py
和得到下面的错误
Traceback (most recent call last):
File "/Users/YxT2/Desktop/PY/Test/main.py", line 7, in <module>
my_appkit_lib.launchMyAppKitWindow()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/Cellar/[email protected]/3.11.3/Frameworks/Python.framework/Versions/3.11/lib/python3.11/ctypes/__init__.py", line 389, in __getattr__
func = self.__getitem__(name)
^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/Cellar/[email protected]/3.11.3/Frameworks/Python.framework/Versions/3.11/lib/python3.11/ctypes/__init__.py", line 394, in __getitem__
func = self._FuncPtr((name_or_ordinal, self))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: dlsym(0x21db45be0, launchMyAppKitWindow): symbol not found
我测试了我的swift代码,它实际上是启动窗口显示在下面的截图。
但是我想用这个测试库来调用python代码中Swift写的launchMyAppKitWindow
函数,谁能帮我解决这个问题?
1条答案
按热度按时间qqrboqgw1#
1.编译AICore. swift。注意:OS X“libAICore.dylib”
--该行出错--
my_appkit_lib = ctypes.CDLL("/Users/YxT2/Desktop/PY/Test/libAICore.dylib")
参考:https://gist.github.com/jiaaro/e111f0f64d0cdb8aca38