Swift uses an instance with the C language pointer _swift

Source: Internet
Author: User
Tags arrays

Objective-c and C APIs often need pointers. The data types in swift natively support the cocoa API based on pointers, and not only that, Swift will automatically handle some of the most commonly used cases where pointers are passed as parameters. In this article, we will look at Swift to have the C language pointer work with variables, arrays, and strings.
### #用以输入/output parameter pointers

C and Objective-c do not support multiple return values, so pointers are often used in the Cocoa API as a way of passing additional data between methods. Swift allows pointers to be used as inout parameters, so you can pass a reference to a variable as a pointer parameter using the symbol &. For example: The Getred (_:green:blue:alpha:) method in Uicolor requires four cgfloat* pointers to receive color composition information, and we use & to capture these constituent information as local variables:

Copy Code code as follows:

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

Another common situation is the customary use of nserror in cocoa. Many methods use a nserror** parameter to store information about possible errors. For example, we use the Nsfilemanager Contentofdirectoryatpath (_:error:) method to list the contents of the directory and point the potential error to a nserror? Variable:
Copy Code code as follows:

var maybeerror:nserror?
If let contents = Nsfilemanager.defaultmanager ()
. Contentsofdirectoryatpath ("/usr/bin", Error: &maybeerror) {
Work with the directory contents
else if let error = Maybeerror {
Handle the error
}

For security purposes, Swift requires that the variables being used & passed are initialized. Because it is not possible to determine if this method will attempt to read data from the pointer before writing the data.

### #作为数组使用的参数指针

In C, arrays and pointers are very tightly connected, and swift allows arrays to be used as pointers, making it easier to work with an array-based C language API. A fixed array can be passed directly with a constant pointer, and a variable array can pass a very variable pointer with the & operator. Just like the input/output parameter pointers. For example, we can use the Vdsp_vadd method in the accelerate framework to add two arrays A and B and write the result to the third array.

Copy Code code as follows:

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, 1, B, 1, &result, 1, 4)

Result now contains [1.5, 2.25, 3.125, 4.0625]

#用作字符串参数的指针

The C language uses cont char* pointers as the basic way to pass strings. A string in swift can be passed to the method as an infinite length UTF-8 encoded const char* pointer. For example: We can pass a string directly to a standard C and POSIX library method

Copy Code code as follows:

Puts ("Hello from libc")
Let FD = open ("/tmp/scratch.txt", o_wronly| O_creat, 0o666)

If FD < 0 {
Perror ("Could not Open/tmp/scratch.txt")
} else {
Let-text = "Hello World"
Write (fd, text, strlen (text))
Close (FD)
}

#指针参数转换的安全性

Swift is working hard to make it easier to interact with C-language pointers because they are widely present in cocoa while maintaining a certain degree of security. However, it is important to use caution when comparing your other SWIFT code with the C-language pointer interaction. Special attention should be paid to:

These conversions are not safe to use if the callee saves the data of the C pointer in order to use it again after it returns a value. The converted pointer is guaranteed to be valid only during the call. Even if you pass the same variable, array, or string as multiple pointer parameters, you will receive a different pointer each time. This exception is stored globally or statically as a variable. You can safely use this address as a permanent and unique pointer. For example: When used as a KVO context parameter.

Overflow checking is not mandatory when the pointer type is array or string. The C-language API cannot increase the size of arrays and strings, so before you pass it on to the C language API, you must make sure that the array or character is the correct size.

If you need to use a pointer-based API without following the instructions, or if you rewrite the cocoa method that accepts pointer parameters, you can use an unsecured pointer in Swift to work with unprocessed memory. In future articles, we will focus on more advanced situations.

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.