Wednesday, December 16, 2015

A bit more about pointers in Swift

I looked into the problems with Open SSL under Swift a bit more. To reassure myself that I can still deal with C pointers, I wrote a quick demo. Here is the gist:



We will print an array passed into the function f1, modify that array in place in f2, and change each value to a different data type and write that to a second array in f3.

f3 takes the fourth root. Because the resulting type is a floating point number (I used a double), I need a second array into which the values are written. It works as you'd expect:


> clang -Wall p1.c -o prog
> ./prog
f1
1 2 3 4 5
f2
1 4 9 16 25
f3
1.00 1.41 1.73 2.00 2.24
>


And the point is that the code to use this C "library" from Swift is trivial. To keep path issues away, I simply added this C file to a new Xcode Cocoa app project written in Swift. I get a bridging header in the usual way, and add to it a statement #import "p.h", as well as dragging the header into the project.

p.h:

void f1(int *, int);
void f2(int *, int);
void f3(int *, double *, int);


To actually use the C code, we just do this in a function called from the AppDelegate:



It prints:


Swift: a = [1, 2, 3, 4, 5]
f1
1 2 3 4 5
f2
f1
1 4 9 16 25
Swift: a = [1, 4, 9, 16, 25]
f3
Swift b: 1.000 1.414 1.732 2.000 2.236


And this code never ever crashes. Well, not that I observed, anyway. I got the idea of testing whether it would crash in 100 trials. In a shellscript:


n=1
while [ $n != 100 ]
do
    open -a "MyApp"
    sleep 1
    osascript -e 'quit app "MyApp"'
    n=$((n+1))
done


open we know, but using osascript to kill an app, that's special.

Although this runs, I got to thinking it probably won't report a crash. I should try Python.



It's actually fairly annoying, because each time the app launches, it grabs the focus!


97
98
99
100
>


That's a relief.

Anyway, it's not hard to puzzle out where we need UnsafeMutablePointer<Int32> and where we need UnsafeMutablePointer<Double>.

Of course, we knew this was robust, because CommonCrypto worked so well.

The problem seems to be in Open SSL. I just started learning to use the debugger lldb. But it is clear that the crash that occurs when we have called AES_set_encrypt_key often occurs sometime later, after the enclosing function test returns, or even back in the AppDelegate. We are not messing up the call.

I don't know how to fix that.