如何在swift中创建UnsafeMutablePointer <unsafemutablepointer>

时间:2017-03-03 17:38:25

标签: swift

功能:

public func OSAtomicCompareAndSwapPtr(_ __oldValue: UnsafeMutableRawPointer!, _ __newValue: UnsafeMutableRawPointer!, ___theValue: UnsafeMutablePointer<UnsafeMutableRawPointer?>!) -> Bool

要求参数UnsafeMutablePointer<UnsafeMutableRawPointer?>使用theValue类型,但我无法确定如何从类型UnsafeMutablePointer<T?>中创建一个<{1}}

关于我如何做到这一点的任何想法?

编辑:

对于我为什么要尝试这样做感到好奇,我正在尝试创建一个通用的包装器,以便在swift中创建一个有界的MPMC队列,如blog post所述。到目前为止,这是我的包装

func compareAndSwap<T: AnyObject>(current: T?, future: T?, toPtr: UnsafeMutablePointer<T?>) -> Bool {
    let currentPtr = current.map(Unmanaged.passUnretained)?.toOpaque()
    let futurePtr = future.map(Unmanaged.passRetained)?.toOpaque()

    if OSAtomicCompareAndSwapPtr(currentPtr, futurePtr, ????) {
        return true
    }
    return false

1 个答案:

答案 0 :(得分:1)

在Swift 3中,use .withMemoryRebound重新诠释&#34; T**&#34;指向&#34; void**&#34;指针:

return toPtr.withMemoryRebound(to: (UnsafeMutableRawPointer?).self, capacity: 1) {
    OSAtomicCompareAndSwapPtr(currentPtr, futurePtr, $0)
}

请注意

  • OSAtomicCompareAndSwapPtr已被弃用,以支持atomic_compare_and_exchange_strongvar toPtr = HOPAtomicReference(object: ...) ... return toPtr.compareTo(current, andSetObject: future) 等C11函数。unfortunately you cannot use in Swift。这是a known issue
  • 博客文章的原子操作使用&#34;获取&#34;,&#34;发布&#34;而且&#34;放松&#34;记忆顺序。 OSAtomic库只提供&#34; seq_cst&#34;和#34;放松&#34; order(每个函数的Barrier vs non-Barrier变体)。因此,您的Swift转换不能是C ++代码的1:1功能副本。

还有一个thin wrapper library timehop/Atomics可以隐藏所有危险的演员阵容(但不是通用的)。

$(function(){
  var ProjType = $("#cfs_i3_cf3");
  $(ProjType).change(function(){
    if($(this).val() == "1")
    {
      $("#cfs_h3").css("background-color", "red");
    }
    else
    {
      $("#cfs_h3").css("background-color", "yellow");
    }
  });
});