IOS: Learning notes, Swift interacts with C-pointers (translate)

Source: Internet
Author: User

Swift interacts with C-pointers

Objective-c and C APIs are often required to use pointers. The SWIFT data type is designed to work naturally with the pointer-based Cocoa API, and Swift actively handles several commonly used pointer parameters. In this article, we'll see how pointer parameters in C work with variables, arrays, and strings in Swift.

pointers as input/output parameters

C and Objective-c do not support multiple return values, so the cocoa API often uses pointers to pass additional parameters to functions. Swift agrees to take the pointer count as a [inout] argument, so you can use the same & syntax to pass a reference to a variable as a pointer. For example: Uicolor's getred (_:green:blue:alpha:) method uses 4 cgfloat* pointers to accept a combination of colors. We can use & to get these values:

0 , g:cgfloat = 0 , b:cgfloat = 0 , a:cgfloat = 0   Color.getred ( &r, Green: &g, Blue: &b, Alpha: &a) 

There is also a common use of nserror. Many methods use the nserror* parameter to save the error that occurred. For example: We enumerate the contents of the folder using the Nsfilemanager Contentsofdirectoryatpath (_:error:) method, directly using the Nserror? variable to save the possible error:

var maybeerror:nserror?ifLet contents = Nsfilemanager.defaultmanager (). Contentsofdirectoryatpath ("/usr/bin", Error: &maybeerror) {      //Content Processing       forIinchcontents{println (i)}}Else ifLet error =maybeerror{//Error Handlingprintln (error.description)}

For security reasons, Swift requires variables to be initialized before they are used &. Because it does not know if the method being called will read the pointer before it changes it

Array pointers

In c the array is tightly connected to the pointer. To facilitate the use of array-based C APIs, Swift agrees to have an array as a pointer. An immutable array can be used as a constant pointer, and the array can be changed to use the & operator as a pointer (as with the InOut parameter). For example: We add two arrays A and b using the Vdsp_vadd function (Accelerte framework) to write the result to the third array result:

Import Accelerate let A: [Float]= [1,2,3,4] Let B: [Float]= [0.5,0.25,0.125,0.0625] var result: [Float]= [0,0,0,0] Vdsp_vadd (A,1B1, &result,1,4)  //result now contains [1.5, 2.25, 3.125, 4.0625]
string pointers

C uses the const char* pointer as the primary way to pass a string. Swift string can be used as a const char* pointer, which will pass a null end to the function, UTF-8 the encoded string pointer. For example, we can pass strings directly to standard C and POSIX library functions:

Puts"Hello from libc") Let FD= Open ("/tmp/scratch.txt", o_wronly|o_creat, 0o666)ifFD <0{perror ("could not open/tmp/scratch.txt")  } Else{Let text="Hello World"Write (fd, text, strlen (text)) Close (FD)}

Security of pointer parameter conversions
Swift makes interaction with the C pointer convenient and provides some security, as the C pointer is everywhere. However, with the C-pointer to each other for the SWIFT code or memory is not secure, so special attention needs to be paid. In particular:
* These conversions cannot safely is used if the callee saves the pointer value for use after it returns. The pointer that results from these conversions are only guaranteed to being valid for the duration of a call. Even if you pass the same variable, array, or string as multiple pointer arguments, you could receive a different pointer Each time. An exception to this is global or static stored variables. You can safely use the address of a global variable as a persistent unique pointer value, e.g.: As a KVO context parameter .
* Array and string pointers do not have bounds checking. The C API does not widen arrays and strings, so you need to allocate enough size for it before calling.

Assuming the above guidelines do not meet the need for your pointer interaction, or if you want to manually control pointer parameters, you can manipulate the memory directly using the unsafe pointer. We'll see a lot of other advanced apps in future articles.

IOS: Learning notes, Swift interacts with C-pointers (translate)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.