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

Source: Internet
Author: User

Swift interacts with C-pointers

Objective-c and C APIs often require pointers. The SWIFT data type is designed to work naturally with the pointer-based Cocoa API, and Swift automatically handles several commonly used pointer parameters. In this article, we'll see how pointer parameters in C work with variables, arrays, 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 allows you to think of pointer parameters as [inout] parameters, 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:float = 0 , b:float = 0 , a:float = 0   Color.getred ( &r, Green: &g, Blue: &b, Alpha: &a) 

Another frequent use is the nserror. Many methods use the nserror* parameter to save the error that occurred. For example: We enumerate the contents of the directory using the Nsfilemanager Contentsofdirectoryatpath (_:error:) method, directly using the Nserror? variable to save the possible errors:

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 modifying it

Array pointers

In c the array is tightly connected to the pointer. To facilitate the use of array-based C APIs, Swift allows an array to be used as a pointer. A non-modifiable array can be used as a constant pointer, and the array can be modified using the & operator as a non-const pointer (just like 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 it as easy as possible to interact with the C pointer and provides some security because the C pointer is everywhere. However, it is not safe for the swift code to cross the C-pointer with each other, which requires special attention. 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.

If the guidelines above do not meet your pointer interaction needs, or if you want to manually control pointer parameters, you can manipulate the memory directly using the unsafe pointer. We'll see more advanced apps in future articles.

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.