c - 使用 calloc 函数快速初始化 UnsafeMutableRawPointer 中的值

标签 c swift

我是 swift 的新手,所以如果你觉得这个问题不合适,请忽略。我只是想在 swift 3.0 中做到这一点

int main()
{
    int i, n;
    int *a;

    printf("Number of elements to be entered:");
    scanf("%d",&n);

    a = (int*)calloc(n, sizeof(int));
    printf("Enter %d numbers:\n",n);
    for( i=0 ; i < n ; i++ ) 
    {
        scanf("%d",&a[i]);
    }

    printf("The numbers entered are: ");
    for( i=0 ; i < n ; i++ ) 
    {
       printf("%d ",a[i]);
    }
    free( a );

    return(0);
}      

我试过了,但运气不好,它说无法将“CChar”的值分配给“UnsafeMutableRawPointer”。谁能帮我?忽略 printf。

typealias set = (CChar, CChar, CChar, CChar, CChar)
let str = "Hello"
var cs = str.cString(using: String.Encoding.utf8)!
var stringSet = set(cs[0], cs[1], cs[2], cs[3], cs[4])
var p = calloc(5, MemoryLayout<CChar>.size)
p = &stringSet.0

谢谢!

最佳答案

这是一个简单的例子。

// Allocate memory for 5 32-bit signed integers in Swift using calloc():
let myPtr = calloc(5, MemoryLayout<Int32>.size)

// Tell Swift how you're going to use the memory:
if let intPtr = myPtr?.bindMemory(to: Int32.self, capacity: 5) {
    // If bindMemory() is successful, place 2 ints in the array
    intPtr[0] = 123;
    intPtr[1] = 321;

    // Give the array to a C function (why would you want to use calloc(), unless 
    // some C code was involved?)
    workWithIntPtr(intPtr)

    // The C function modified the array, see what happened:
    print("After calling C code, the 3rd element of the array is \(intPtr[2])")
}

C 函数在这里:

void workWithIntPtr( int32_t * p)
{
    printf("The 1st 2 elements of the array are %d\n and %d\n", p[0], p[1]);
    p[2] = 555;
}

请参阅相关的 Swift 和 C 文档。当然,C 代码需要通过桥接 header 暴露给 Swift。希望这对您有所帮助,祝您好运。

关于c - 使用 calloc 函数快速初始化 UnsafeMutableRawPointer 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40925776/

相关文章:

c - 如何添加循环?

c - 纯 C 标准输入缓冲区垃圾和换行符

swift - Swift 3 中的可扩展 UIBezierpath

UITableViewHeaderView 默认卡在单元格上方,而不是上方

ios - Apple Pay token 的交易金额不正确

c - 如何获取execlp的退出代码

C 编译器警告 Unknown escape sequence '\.' using regex for c program

ios - 创建框架时如何访问 AppDelegate 方法 handleEventsForBackgroundURLSession

c - C中局部变量的返回地址

arrays - 获取 JSON 数组内的 UICollectionView 单元格 ID 并将其设为全局