使用calloc函数在swift中初始化UnsafeMutableRawPointer中的值

时间:2016-12-02 06:02:08

标签: 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);
}      

我已经尝试了这个,但没有运气,它说不能分配&#39; CChar&#39; to&#39; UnsafeMutableRawPointer&#39;。谁能帮我?忽略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

谢谢!

1 个答案:

答案 0 :(得分: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代码需要通过桥接头暴露给Swift。希望这有帮助,祝你好运。