我尝试在cpp类中执行某些操作,并且在执行该函数时将回调返回swift。
所以我做这些事情:
在callbackClass.cpp
int callback::run(void (*callback)(int))
{
for (unsigned int i = 0; i < 100; i++)
{
callback(i);
}
return 0;
}
在callbackClass.hpp
中:
class callbackClass.hpp
{
.
.
.
public:
int run(void (*callback)(int));
};
#endif
对于header.h
:
int callback(void (*callback)(int));
在Swift
端记录回调之前,这是很好的:
func callbackFunc(){
callback({valueFromCallback in //call cpp function
print(valueFromCallback) //Works fine
})
}
但是当尝试做其他事情时:
func callbackFunc(){
var value : String!
callback({valueFromCallback in //call cpp function
value = String(valueFromCallback) //It has a problem
})
}
Xcode返回此错误:
不能从捕获上下文的闭包中形成C函数指针
我已经看过这些问题,但没有帮助:
Swift: Pass data to a closure that captures context
How to cast self to UnsafeMutablePointer<Void> type in swift
A C function pointer cannot be formed from a closure that captures context
答案 0 :(得分:0)
最终我意识到可以将'closure'作为参数传递给c ++
因此,首先我在Swift类中创建一个Closure:
typealias closureCallback = (Int32) -> ()
然后将其传递给cpp端:
在header.h
int callback(void (^closureCallback)(int));
在callbackClass.hpp
中:
class callbackClass.hpp
{
.
.
.
public:
int run(void (^closureCallback)(int));
};
#endif
在callbackClass.cpp
int callback::run(void (^closureCallback)(int))
{
for (unsigned int i = 0; i < 100; i++)
{
closureCallback(i);
}
return 0;
}
最后在Swift中处理它:
typealias closureCallback = (Int32) -> ()
func callbackFunc(){
var value : String!
let closureValue: closureCallback = {valueFromclosureCallback in
value = String(valueFromclosureCallback)
}
callback(closureValue) //call cpp function
}