Dan*_*Dan 13 c callback wrapper swift
从Swift调用C非常简单,但我正在研究在C中制作双向包装器,所以我的C必须调用Swift函数.
现在,我可以通过在C中声明函数指针来实现这一点,并且在Swift端将它们设置为在Swift中调用代码之后让我的C函数调用它们.
我的C头文件:
typedef void (*callback_t)(void);
void callBackIntoSwift( callback_t cb );
Run Code Online (Sandbox Code Playgroud)
我的C实现文件:
#include "stuff.h"
#include <stdio.h>
void callBackIntoSwift( callback_t cb )
{
printf( "Will call back into Swift\n" );
cb();
printf( "Did call back into Swift\n" );
}
Run Code Online (Sandbox Code Playgroud)
在桥接头中包含我的C头文件后,我可以在Swift端执行以下操作:
let cb: callback_t = {
someKindOfSwiftFunction()
}
callBackIntoSwift( cb )
Run Code Online (Sandbox Code Playgroud)
甚至:
callBackIntoSwift {
someKindOfSwiftFunction()
}
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来做到这一点,不需要函数指针和回调?我想让C端someKindOfSwiftFunction直接调用...但是当我尝试应用于@convention (c)函数声明时,我得到的消息是该属性只能应用于类型,而不是声明.
例如Github中的任何想法或代码库我都可以看看?
根据Joe Groff的说法:
还没有官方的方法。除了名称处理之外,Swift函数还使用了与C不同的调用约定。非官方地,如果您愿意处理比通常的代码破坏和编译器错误更多的工作,那么有一个非官方的属性@_cdecl可以做到这一点:
@_cdecl("mymodule_foo")
func foo(x: Int) -> Int {
return x * 2
}
Run Code Online (Sandbox Code Playgroud)
然后可以从C调用:
#include <stdint.h>
intptr_t mymodule_foo(intptr_t);
intptr_t invoke_foo(intptr_t x) {
return mymodule_foo(x);
}
Run Code Online (Sandbox Code Playgroud)
小智 0
你可以这样做:
文件Swift.swift
public class SwiftTest: NSObject {
@objc public static func testMethod() {
print("Test")
}
}
Run Code Online (Sandbox Code Playgroud)
文件SwiftWrapper.h
void SwiftFunctionWrapper();
Run Code Online (Sandbox Code Playgroud)
文件SwiftWrapper.m
#import "ProductModuleName-Swift.h"
void SwiftFunctionWrapper() {
[SwiftTest testMethod];
}
Run Code Online (Sandbox Code Playgroud)