[Swift vs C] Basic variables interaction (Array MutablePointer)
Here some example codes interacting Array and pointer variables between Swift and C.
Basically, Swift can receive pointer from C and vice vasa.
Basic
C
int *intp()
{
int i;
int *p = calloc(sizeof(int),100);
for(i=0;i<100;i++){
p[i] = i;
}
return p;
} //for deallocation
int *free_intp(int *p)
{
free(p);
return p;
}
swift
var IntPointer = UnsafeMutablePointer() IntPointer = intp() for i in 0..<100{
println(IntPointer[i])
} IntPointer = free_intp(IntPointer)
Array
C can only send pointers to Swift and then Swift received it as UnsafeMutablePointer
In the opposite case, Swift can send UnsafeMutablePointer directly to swift or otherwise the pointer of Array to C, then C received it as pointer
C
void GetMutablePointer(int *a)
{
int i;
for(i=0;i<10;i++){
printf("%d\n",a[i]);
}
}
Swift
//allocate
var IntPointer = UnsafeMutablePointer().alloc(10) for i in 0..<10{
IntPointer[i] = i
}GetMutablePointer(IntPointer)
This is how to send UnsafeMutablePointer to C
or below's example shows how to send Array of Swift to C
Swift
var intArray = Array<Int>()
for i in 0..<10{
intArray.append(i)
} GetMutablePointer(&intArray)

0 コメント: