gpt4 book ai didi

c++ - 如何将 Swift 与 C 或 C++ 连接?

转载 作者:行者123 更新时间:2023-11-30 21:45:49 29 4
gpt4 key购买 nike

我想用 C 或 C++ 编写一些 native 代码,以便与 iOS 上的 Swift 一起使用。该代码主要从 Swift 调用,但也需要回调到 Swift。

Swift 与这两种语言的接口(interface)机制是什么?

C 或 C++ 中哪一个在这种接口(interface)中具有最少的约束,为什么?跨语言调用有性能差异吗?

最佳答案

interoperability of swift使用 C 或 C++ 超越 Objective-C,通过 bridging header

在此 Objective-C header 中,您可以包含 C header ,因为 Objective-C 可以与 C 互操作。然后 Swift 不仅可以使用 C functions ,还可以使用 C structures and unions .

您还可以使用 Objective-C++ 来实现与 C++ 的互操作性。哇,Objective-C 和 Swift 都不能使用 C++ 类及其语义。因此,您将面临与尝试从 C 使用 C++ 时相同的问题。在 this 中和 this答案,您将找到有关 C++ 互操作性的更多信息。

那么从/到 Swift 调用什么更容易呢?绝对是C

<小时/>

小型分步演示:

1) 在 XCode 中创建 Swift 项目
2)添加c文件test.c
3) 当您添加c文件后,XCode会询问您是否要创建桥接头:只需确认即可。
4)使用以下代码

在桥接 header 中(或在桥接 header 中包含的 header 中):

// C functions
int myCFunction(int a);
void myCFunctionWithCallback(int a, int (*f)(int));

// Swift functions accessible from C
extern int mySwiftFunction(int x);

示例test.c文件:

#include <stdio.h>

// simple example with a hardcoded swift callback
int myCFunction(int a)
{
printf ("myCFunction in C called with %d\n", a);
printf ("Now calling Swift from C :\n");
int z = mySwiftFunction(10);
printf ("Result returned in C:%d\n", z);
return 2*a;
}

// example with a function pointer to a swift callback
void myCFunctionWithCallback(int a, int (*f)(int))
{
printf ("myCFunctionWithCallback in C called with %d\n", a);
printf ("Now calling Swift from C :\n");
int z = f(a);
printf ("Result returned in C:%d\n", z);
}

示例main.swift文件:

import Foundation

@_silgen_name("mySwiftFunction") // vital for the function being visible from C
func mySwiftFunction(x: Int) -> Int
{
print ("mySwiftFUnction called in Swift with \(x)")
return 3*x
}

func mySwiftCallback(x: Int32) -> Int32
{
print ("mySwiftCallback called in Swift with \(x)")
return 7*x
}

print("Starting Swift/C interoperability demo !")
let a = myCFunction(12);
print ("returned result in Swift is \(a)")

print ("Now test with a callback function pointer:")
myCFunctionWithCallback(13, mySwiftCallback )

使 swift 函数在 C 中可见的技巧 @_silgen_namethis other SO answer 中进行了解释。并记录在here

关于c++ - 如何将 Swift 与 C 或 C++ 连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55890187/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com