我有一个用 Swift 编写的函数,我想从 Rust 调用它。我已经尝试通过 Objective-C 公开它,但是我继续收到 ld
的错误,说它找不到 _foo
。通过将 Rust 项目编译为静态库,将 Rust 项目链接到 Swift 项目。
foo.h
#pragma once
#include <stdint.h>
uint8_t foo_bridge(uint8_t);
foo.m
#import <Foundation/Foundation.h>
#import <Foo-Swift.h>
uint8_t foo_bridge(uint8_t byte) {
return foo(byte);
}
酒吧. swift
public func foo(byte: UInt8) -> UInt8 {
return byte * 2
}
源文件/lib.rs
extern "C" {
pub fn foo_bridge(byte: u8) -> u8;
}
Bar-Bridging-Header.h
#import "foo.h"
cargo .toml
[package]
name = "foo"
version = "0.1.0"
[lib]
name = "foo"
crate-type = ["staticlib"]
最佳答案
这里的问题是试图从不支持的 Objective-C 调用裸 Swift 函数。
如果您检查 Foo-Swift.h
header ,您会发现 foo()
函数不存在,这表明它的符号, _foo
,在运行时也不可用。
解决方案是将 foo()
函数放在可以从 Objective-C 调用的东西中,比如从 NSObject 派生的类:
class Foo: NSObject {
class func foo(byte: UInt8) -> UInt8 {
return byte * 2
}
}
完成后,您会发现 Foo-Swift.h
header 现在有一个接口(interface):
@interface Foo : NSObject
+ (uint8_t)fooWithByte:(uint8_t)byte;
- (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER;
@end
因为我们知道它现在可以从 Objective-C 获得,所以我们可以这样调用它:
uint8_t foo_bridge(uint8_t byte) {
return [Foo fooWithByte:byte];
}
关于objective-c - 如何在 Rust 中调用 Swift 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42903037/