Calling C function from Swift version 5.3: using pthreads

Viewed 179

EDIT3: Recreating the error from RDerik's code

I originally started with code I modified from RDerik. Now, others might recreate the error, I am running unmodified code from RDerik cloned from here.

When I run RDerik's code I get the following errors(same errors I noted in EDIT: below):

error: value of optional type 'pthread_t?' (aka 'Optional') must be unwrapped to a value of type 'pthread_t' (aka 'UInt')

note: force-unwrap using ! to abort execution if the optional value contains nil

error: cannot convert value of type '(UnsafeMutableRawPointer) -> UnsafeMutableRawPointer?' to expected argument type '@convention(c) (UnsafeMutableRawPointer?) -> UnsafeMutableRawPointer?' let result = pthread_create(&myThread, nil, threadedFunction, pThreadParameter)

I solved this last error by changing the function header of threadedFunction() to:

func threadedFunction(pointer: UnsafeMutableRawPointer!) -> UnsafeMutableRawPointer? 

ORIGINAL POST:

I know this question has been answered before but I haven't been able to find a fix compatable with Swift 5.3. The C function I need to call has this signature:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg)

Line 5 below is my Swift attempt at calling pthread_create(). Specifically my problem is with the first parameter: &myThread.

MY CODE: (modified from here)

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)

ERROR:

When calling pthread_create the myThread parameter throws the following error: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value, line 5

EDIT:

Other things I've tried:

If I use a ? instead of ! for pthread like this:

    var myThread: pthread_t? = nil

I get compile errors:

error: value of optional type 'pthread_t?' (aka 'Optional') must be unwrapped to a value of type 'pthread_t' (aka 'UInt')

note: force-unwrap using '!' to abort execution if the optional value contains 'nil'

EDIT2:

Also tried:

    let result = pthread_create(&myThread, 0, __threadedFunction, pThreadParameter)

ERROR: cannot convert value of type 'Int' to expected argument type 'UnsafePointer<pthread_attr_t>?'

1 Answers

I dont know swift. However the corresponding to NIL is NULL in c.NULL again is a macro, depending on the compiler. So it can either be defined as #define NULL ((char *)0) or simply #define NULL 0. So what happens if you pass pthread_create(&myThread, 0, ... instead of nil?

Related