cswiftbridging-headerunsafemutablepointer

Converting UnsafeMutablePointer to an Array gives wrong value


I'm using Swift and should I use C source with Bridging-Header.

C source has like this function.

char* testFunc2(char *input) { // input = [4, 5, 6, 7, 8, 9]
    char v1[17] = { 0, };

    memcpy(v1, input, 4);

    return (char*)v1; 
}

The v1's value will be [4, 5, 6, 7, 0, 0, 0...]

And I input data like this

var i1: [Int8] = [4, 5, 6, 7, 8, 9]
let idPtr = UnsafeMutablePointer<Int8>.allocate(capacity: 7)
idPtr.initialize(from: &i1, count: 6)

let tf2 = testFunc2(idPtr)

The address value is equal (char*)v1 with tf2.

But when I converted tf2(UnsafeMutablePointer) to Array,

the value is different.

I converted like this

let tt2Buf = UnsafeMutableBufferPointer(start: tt2, count: 17)
let tt2Arr = Array(tt2Buf)

When I return input(parameter) directly, converted value is right.

But when I did somegthing in C source and returned value,

the converted value is not correct with return value in C source.

I wasted day about 10 days with this problem....

How can I Do.....?


Solution

  • char v1[17] is local array, its scope is limited to testFunc2 function. You cannot use its reference outside the function.

    Maybe you can allocate memory dynamically and pass its reference.

    char* testFunc2(char *input) { // input = [4, 5, 6, 7, 8, 9]
        char *v1 = malloc(17);
    
        memset(v1, 0, 17);
        memcpy(v1, input, 4);
    
        return v1; 
    }
    

    However you have to free the memory at some point otherwise you will have memory leaks.