在没有 unsafeBitCast 的情况下将 UnsafeMutablePointer 值分配给 UnsafePointer

Assigning UnsafeMutablePointer value to UnsafePointer without unsafeBitCast

我正在使用 C API 工作,它定义了一个带有 const char* 的结构和一个 returns 一个 char* 的函数,我正在尝试找到进行赋值的最佳方法。

有没有不使用 unsafeBitCast 的方法?如果我不进行转换,则会出现此错误:

Cannot assign value of type 'UnsafeMutablePointer<pchar>' 
(aka 'UnsafeMutablePointer<UInt8>') 
to type 'UnsafePointer<pchar>!' 
(aka 'ImplicitlyUnwrappedOptional<UnsafePointer<UInt8>>')

此外,下面使用 pair() 的 pairPtr 的初始化是否会在堆栈上分配一对结构以初始化堆上分配的对,因为这对于只需要将结构清零的情况来说似乎效率低下.

示例代码如下:

C 库头文件(最小化以演示问题):

#ifndef __PAIR_INCLUDE__
#define __PAIR_INCLUDE__

typedef unsigned char pchar;

pchar*
pstrdup(const pchar* str);

typedef struct _pair {
    const pchar* left;
    const pchar* right;
} pair;

#endif // __PAIR_INCLUDE__

我的Swift代码:

import pair

let leftVal = pstrdup("left")
let rightVal = pstrdup("right")

let pairPtr = UnsafeMutablePointer<pair>.allocate(capacity: 1)
pairPtr.initialize(to: pair())

// Seems like there should be a better way to handle this:
pairPtr.pointee.left = unsafeBitCast(leftVal, to: UnsafePointer<pchar>.self)
pairPtr.pointee.right = unsafeBitCast(rightVal, to: UnsafePointer<pchar>.self)

C代码:

#include "pair.h"
#include <string.h>

pchar*
pstrdup(const pchar* str) {
    return strdup(str);
}

模块定义:

module pair [extern_c] {
    header "pair.h"
    export *
}

您可以从 UnsafeMutablePtr<T> 创建一个 UnsafePointer<T> 只需

let ptr = UnsafePointer(mptr)

使用

/// Creates an immutable typed pointer referencing the same memory as the
/// given mutable pointer.
///
/// - Parameter other: The pointer to convert.
public init(_ other: UnsafeMutablePointer<Pointee>)

UnsafePointer 的初始化程序。在你的情况下,例如

p.left = UnsafePointer(leftVal)