ios 如何设置和获取指针 Swift 的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25660299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 02:12:20  来源:igfitidea点击:

How to set & get value of pointer Swift

iosobjective-cxcodeswift

提问by Giang

In Objetive-C when I want set/change value of pointer. I use

在 Objetive-C 中,当我想设置/更改指针值时。我用

*pointer = value

But In Swift, how to get/set value of pointer?

但是在 Swift 中,如何获取/设置指针的值?

I'm woking with bitmap pixel:

我正在使用位图像素:

  NSUInteger offsetPixelCountForInput = ghostOrigin.y * inputWidth + ghostOrigin.x;
  for (NSUInteger j = 0; j < ghostSize.height; j++) {
    for (NSUInteger i = 0; i < ghostSize.width; i++) {
      UInt32 * inputPixel = inputPixels + j * inputWidth + i + offsetPixelCountForInput;
      UInt32 inputColor = *inputPixel;

      newR = MAX(0,MIN(255, newR));
      newG = MAX(0,MIN(255, newG));
      newB = MAX(0,MIN(255, newB));

        *inputPixel = RGBAMake(newR, newG, newB, A(inputColor));
    }
  }

So I want to convert this code into Swift, but I'm stuck with pointers.

所以我想把这段代码转换成 Swift,但我被指针困住了。

23.03.2016 - Update code

23.03.2016 - 更新代码

var inputPixels:UnsafeMutablePointer<UInt32> = nil
inputPixels = UnsafeMutablePointer<UInt32>(calloc(inputHeight * inputWidth, UInt(sizeof(UInt32))))

回答by Kostiantyn Koval

You can work with pointers in Swift. There are UnsafePointerand UnsafeMutablePointergeneric types.

您可以在 Swift 中使用指针。有UnsafePointerUnsafeMutablePointer泛型类型。

Here is a function that takes a floatpointer
You can use float variable and pass it's address &floatVar
or you can create and allocate an UnsafeMutablePointerand pass it. But you have to manually allocate and deallocate memory.

这是一个带有float指针的函数
您可以使用浮点变量并传递它的地址,&floatVar
或者您可以创建并分配一个UnsafeMutablePointer并传递它。但是您必须手动分配和释放内存。

When you work with an UnsafeMutablePointerpointer type and want to assign some value to it you have to do the following:

当您使用UnsafeMutablePointer指针类型并希望为其分配一些值时,您必须执行以下操作:

  • check if points to some variable (not nil)
  • Assign your value to the memoryproperty
  • 检查是否指向某个变量(非零)
  • 将您的价值分配给该memory物业

Code Example:

代码示例:

func work (p: UnsafeMutablePointer<Float>) {
    if p != nil {
      p.memory = 10
    }
    println(p)
    println(p.memory)
  }

var f: Float = 0.0
var fPointer: UnsafeMutablePointer<Float> = UnsafeMutablePointer.alloc(1)

work(&f)
work(fPointer)
fPointer.dealloc(1)

回答by Roman

You should use pointeeproperty instead of memoryin Swift 3

您应该在 Swift 3 中使用指针属性而不是内存

pointer.pointee = value