Swift调用C调用Swift? [英] Swift call C call Swift?

查看:71
本文介绍了Swift调用C调用Swift?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

其他人已经讨论了如何从Swift调用C代码,并且效果很好.其他人也讨论了如何将Swift作为C代码的子例程调用是一个坏主意,因为需要设置整个Swift运行时.

但这是我的问题:如果我的程序基于Swift,并调用了C子例程,但想为这些子例程提供回调,那可能吗?如果这些C子例程采用C兼容的类型化参数(CInt等),那么这些C子例程可以按名称调用Swift例程吗?

此外,C和Swift可以共享全局变量吗?朝哪个方向?

解决方案

做这种事情的公认方法是将快速函数/闭包分配给C函数指针.

但是,如果您查看Swift源代码,它将在多个地方使用未记录的 @_ silgen_name 属性为swift函数提供与C兼容的名称,因此可以直接从C和C ++调用它们

这可行(在XCode 9 beta中测试)

main.c

 //声明函数.您可能会将其放在.h中int mySwiftFunc(int);int main(int argc,const char * argv []){int retVal = mySwiftFunc(42);//调用swift函数printf(你好,来自C:%d",retVal);返回0;} 

SomeSwift.swift

  @_ silgen_name("mySwiftFunc")//为函数指定C名称public func mySwiftFunc(number:Int)->诠释{print(您好,来自Swift:\(number)")返回69} 

但是考虑到它没有文档,您可能不想使用它,并且它可以使用哪些函数签名和参数类型有些模糊.ABI稳定的人吗?

Others have discussed how to call C code from Swift, and it works nicely. Others have also discussed how calling Swift as a subroutine to C code is a bad idea, because the whole Swift runtime would need to be set up.

But here's my question: if my program is based in Swift, and calls C subroutines, but would like to provide callbacks for those subroutines, is that possible? And could those C subroutines call Swift routines by name, provided that they took C compatible typed parameters (CInt, etc)?

Also, can C and Swift share global variables? In either direction?

解决方案

The approved way to do this kind of thing is assigning swift functions/closures to C function pointers.

But if you look at the Swift source code, it uses the undocumented @_silgen_name attribute in several places to give swift functions C compatible names, so they can be called directly from C and C++

So this works (tested in XCode 9 beta)

main.c

// declare the function. you would probably put this in a .h
int mySwiftFunc(int);

int main(int argc, const char * argv[]) {

    int retVal = mySwiftFunc(42); // call swift function
    printf("Hello from C: %d", retVal);

    return 0;
}

SomeSwift.swift

@_silgen_name("mySwiftFunc") // give the function a C name
public func mySwiftFunc(number: Int) -> Int
{
    print("Hello from Swift: \(number)")
    return 69
}

But given it's undocumented you probably don't want to use it, and it's a bit murky on what function signatures and parameter types it will work with. ABI stability anyone??

这篇关于Swift调用C调用Swift?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆