EDIT3: 从RDerik的代码中重新创建错误。
我最初使用了我从RDerik修改的代码。现在,其他人可能会重新创建错误,我正在运行从这里克隆的未经修改的RDerik代码。
当我运行RDerik的代码时,我会得到以下错误(与下面的EDIT中指出的相同错误):
错误:可选类型“pthread_t?”(即“Optional”)的值必须解包为类型“pthread_t”(即“UInt”)的值
注意:使用
!
进行强制解包,如果可选值包含nil
,则终止执行
错误:无法将类型为“(UnsafeMutableRawPointer) -> UnsafeMutableRawPointer?”的值转换为预期的参数类型“@convention(c) (UnsafeMutableRawPointer?) -> UnsafeMutableRawPointer?” let result = pthread_create(&myThread, nil, threadedFunction, pThreadParameter)
我通过更改threadedFunction()
的函数头来解决了这个最后一个错误:
func threadedFunction(pointer: UnsafeMutableRawPointer!) -> UnsafeMutableRawPointer?
原帖:
我知道这个问题以前已经得到过解答,但我还没有找到一个适用于Swift 5.3的fix。我需要调用的C函数具有以下签名:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg)
以下是我尝试使用Swift调用
pthread_create()
的代码,第5行是关键:参数&myThread
。请参考以下修改自这里的代码:var myThread: pthread_t! = nil
var threadParameter = _ThreadParameter(threadIdentifier: _ThreadIdentifier(id: ""), pxT: self)
var pThreadParameter = UnsafeMutablePointer<_ThreadParameter>.allocate(capacity:1)
pThreadParameter.pointee = threadParameter
let result = pthread_create(&myThread, nil, __threadedFunction, pThreadParameter)
错误:
调用pthread_create时,myThread参数抛出以下错误: 致命错误:在第5行隐式解包可选值时意外地发现了nil
编辑:
我尝试过的其他事情:
如果我像这样使用?
而不是!
来处理pthread:
var myThread: pthread_t? = nil
我遇到了编译错误:
``` 错误: 可选类型的值 'pthread_t?' (即 'Optional') 必须被解包为类型为 'pthread_t' (即 'UInt') 的值。 ```
提示:使用 '!' 强制解包,如果可选值包含 'nil' 则中止执行。 编辑2: 我还尝试过:
let result = pthread_create(&myThread, 0, __threadedFunction, pThreadParameter)
错误:无法将类型为“Int”的值转换为预期的参数类型“UnsafePointer<pthread_attr_t>?”
pthread_create
,而不使用Swift可用的其他并发范例(例如Dispatch)之一? - Itai Ferber