<div dir="ltr">Hey Chris,<div><br></div><div>So I work with a C library and Swift as well and have a couple of ideas for you depending on how you work with the array. Here are some tricks I have used when passing around arrays from C to Swift to ObjC and never had issues with it. Also, while passing in the first element of the tuple is fine since the first element has the same address as the entire array in C, I would just use the base tuple instead as it is more Swifty.</div><div><br></div><div>You will have to specify the result type of the functions but it is better than using several closures to get to where you want to work with stuff. Removing closures will also help you debug it and see if something else is going on because if you are passing in the first element all the way down and not modifying the pointer your logic should be correct.</div><div><br></div><div>If you don't mind making a deep copy into a native Swift array you can use a function like this to work with any C array:</div><div><br></div><div><br></div><div>func tupleValuesToArray<T, U>(_ tuple: T) -> U {</div><div> var toReturn: [U] = []</div><div> for (_, value) in Mirror(reflecting: tuple).children {</div><div> if let value = value as? U {</div><div> toReturn.append(value)</div><div> } else {</div><div> fatalError("Failed to convert \(tuple) into an array")</div><div> }</div><div> }</div><div> return toReturn</div><div>}</div><div><br></div><div>let swiftArray: [Float] = tupleValuesToArray(comeCArray)</div><div><br></div><div><br></div><div>If you need to mutate the array or if you just don't want to copy it and/or want to access it as a sequence you should use an Unsafe[Mutable]BufferPointer. You can convert to one with this function:</div><div><br></div><div><br></div><div>func tupleToUnsafe[Mutable]Buffer<T, U>(_ tuple: Unsafe[Mutable]Pointer<T> -> Unsafe[Mutable]BufferPointer<U> {</div><div> let mirror = Mirror(reflecting: tuple.poinee)</div><div> return Unsafe[Mutable]BufferPointer<U>(start: Unsafe[Mutable]Pointer(OpaquePointer(tuple)), count: Int(mirror.children.count))</div><div>}</div><div><br></div><div>let buffer: UnsafeMutableBufferPointer<Float> = tupleToUnsafeMutableBuffer(&cArrayAsTuple)<br></div><div><br></div><div><br></div><div>So there are a few things to point out with this function. You have to get around type checking by converting to an OpaquePointer and back in order to cast from T -> U.. There are other solutions to get around the type checks but this is the one I often use even though I dislike it...</div><div><br></div><div>Anyways, once you have a buffer you should then be able to pass in the baseAddress (and count) of the buffer to ObjC and have it work fine so long as no pointer math is messing it up down inside the other parts of your code.</div><div><br></div><div><br></div></div><div class="gmail_extra"><br><div class="gmail_quote">On Thu, Sep 21, 2017 at 7:33 AM, Johannes Weiß via swift-users <span dir="ltr"><<a href="mailto:swift-users@swift.org" target="_blank">swift-users@swift.org</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">Hi Chris,<br>
<br>
Yes, he'll need to do<br>
<br>
withUnsafeMutablePointer(to: &inReq.imageInfo.<wbr>transformation) { transformationTuplePtr in<br>
withUnsafeMutablePointer(to: &inReq.imageInfo.projection) { projectionTuplePtr in<br>
transformationTuplePtr.<wbr>withMemoryRebound(to: Float.self, capacity: 16) { transformationArrayPtr in<br>
projectionTuplePtr.<wbr>withMemoryRebound(to: Float.self, capacity: 16) { projectionArrayPtr in<br>
....imageReceived(..., transform: transformationArrayPtr, projection: projectionArrayPtr, ...)<br>
}<br>
}<br>
}<br>
}<br>
<br>
if you need access to 5 of them, you'll need to nest deeper, apologies.<br>
<br>
However, there's talk on swift-evolution about getting fixed-size arrays into Swift which would help here. But there's no full proposal yet AFAIK.<br>
<br>
<br>
-- Johannes<br>
<div class="HOEnZb"><div class="h5"><br>
> On 21 Sep 2017, at 2:27 pm, Chris McIntyre <<a href="mailto:nothingwasdelivered@gmail.com">nothingwasdelivered@gmail.com</a><wbr>> wrote:<br>
><br>
> Sorry to jump in here, and maybe I’m missing something obvious, but in your example Rick is two levels of closure deep and only has access to one of the arrays in his struct. In this case there is another array of floats he needs as an argument to his method call. Will he need to go through the same steps, going two levels of closure deeper, before he has access to both struct members?<br>
><br>
> This doesn’t seem to scale very well. What about a struct with 5 arrays?<br>
> --<br>
> Chris McIntyre<br>
><br>
><br>
><br>
><br>
>> On Sep 21, 2017, at 6:05 AM, Johannes Weiß via swift-users <<a href="mailto:swift-users@swift.org">swift-users@swift.org</a>> wrote:<br>
>><br>
>> Hi Rick,<br>
>><br>
>>> On 21 Sep 2017, at 1:03 am, Rick Mann via swift-users <<a href="mailto:swift-users@swift.org">swift-users@swift.org</a>> wrote:<br>
>>><br>
>>> I've got Swift code wrapping a C API. One of the C structs the API uses looks like this:<br>
>>><br>
>>> typedef struct {<br>
>>> size_t size;<br>
>>> float transformation[16];<br>
>>> float projection[16];<br>
>>> uint32_t width;<br>
>>> uint32_t height;<br>
>>> } image_info_t;<br>
>>><br>
>>> In Swift, the two array members are 16-tuples of floats. Eventually, the Swift code calls an Objective-C delegate, passing a tuple to an array:<br>
>>><br>
>>> self.delegate?<br>
>>> .imageReceived(self,<br>
>>> index: inReq.imageIndex,<br>
>>> data: data,<br>
>>> width: width,<br>
>>> height: height,<br>
>>> transform: &inReq.imageInfo.<wbr>transformation.0,<br>
>>> projection: &inReq.imageInfo.projection.0)<br>
>><br>
>> these are illegal. You're getting a pointer to _only_ the first element (&inReq.imageInfo.<wbr>transformation.0) but the library will then read 16 elements from there.<br>
>><br>
>> Something like this should work (and is legal):<br>
>><br>
>> withUnsafeMutablePointer(to: &inReq.imageInfo.<wbr>transformation) { tupleOfFloatsPtr in<br>
>> tupleOfFloatsPtr.<wbr>withMemoryRebound(to: Float.self, capacity: 16) { arrayOfFloatsPtr in<br>
>> ....imageReceived(..., transform: arrayOfFloatsPtr, ...)<br>
>> }<br>
>> }<br>
>><br>
>> that's legal because now we're capturing a pointer to the whole tuple and therefore Swift guarantees the memory to be in C standard layout.<br>
>><br>
>><br>
>><br>
>>><br>
>>> This seems to have been working fine for a long time, but we're running into a crash in some cases, and so I've been digging into it. I turned on the address sanitizer, and I consistently get it to trip in some C++ code that eventually gets called with a float* to that transform tuple.<br>
>>><br>
>>> Now, in Swift, the values of the tuple look great:<br>
>>><br>
>>> ▿ 16 elements<br>
>>> - .0 : 0.548282921<br>
>>> - .1 : 0.821425974<br>
>>> - .2 : -0.156990349<br>
>>> - .3 : 0.0<br>
>>> - .4 : -0.277842015<br>
>>> - .5 : 0.00185899995<br>
>>> - .6 : -0.960625231<br>
>>> - .7 : 0.0<br>
>>> - .8 : -0.788789928<br>
>>> - .9 : 0.570312977<br>
>>> - .10 : 0.229245573<br>
>>> - .11 : 0.0<br>
>>> - .12 : 0.0475889929<br>
>>> - .13 : -0.0323969983<br>
>>> - .14 : -0.0113521963<br>
>>> - .15 : 1.0<br>
>>><br>
>>> I can see this by clicking up the stack a couple frames to the Swift code. But the Objective-C(++) delegate code, that gets passed a float*, sees this (BTW, I can't figure out how to get the debugger, Xcode or command line, to display inTransform as an array of 16 floats). It's clearly not the same array.<br>
>>><br>
>>><br>
>>> (lldb) po inTransform[0]<br>
>>> 0.548282921<br>
>>><br>
>>> (lldb) po inTransform[1]<br>
>>> 0.0343905278<br>
>>><br>
>>> (lldb) po inTransform[2]<br>
>>> -0<br>
>>><br>
>>> (lldb) po inTransform[3]<br>
>>> 0<br>
>>><br>
>>> (lldb) po inTransform[4]<br>
>>> 0<br>
>>><br>
>>> (lldb) po inTransform[5]<br>
>>> 0<br>
>>><br>
>>> (lldb) po inTransform[6]<br>
>>> 95488384<br>
>>><br>
>>> (lldb) po inTransform[14]<br>
>>> 0.<wbr>000000000000000000000000000000<wbr>00000000000000560519386<br>
>>><br>
>>> (lldb) po inTransform[15]<br>
>>> 0<br>
>>><br>
>>> The address sanitizer spits out this:<br>
>>><br>
>>> ==============================<wbr>==============================<wbr>=====<br>
>>> ==1358==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x00014d3ea224 at pc 0x000100eb9a84 bp 0x00016fd84bd0 sp 0x00016fd84bc8<br>
>>> READ of size 4 at 0x00014d3ea224 thread T0<br>
>>> #0 0x100eb9a83 in <redacted>::addImage(void const*, int, int, int, float const*, float const*) (<redacted>:arm64+0x100e41a83)<br>
>>> #1 0x10040b72b in -[<redacted> imageReceived:index:data:<wbr>width:height:transform:<wbr>projection:] (<redacted>:arm64+0x10039372b)<br>
>>> #2 0x10045d037 in function signature specialization <Arg[0] = Owned To Guaranteed, Arg[1] = Owned To Guaranteed, Arg[2] = Owned To Guaranteed and Exploded> of closure #1 () -> () in <redacted>.imageDownloaded(<<wbr>redacted>.<wbr>DownloadImageRequest, index: Swift.Int) -> () (<redacted>:arm64+0x1003e5037)<br>
>>> #3 0x100442bbb in closure #1 () -> () in <redacted>.imageDownloaded(<<wbr>redacted>.<wbr>DownloadImageRequest, index: Swift.Int) -> () (<redacted>:arm64+0x1003cabbb)<br>
>>> #4 0x10043e7fb in reabstraction thunk helper from @callee_owned () -> () to @callee_unowned @convention(block) () -> () (<redacted>:arm64+0x1003c67fb)<br>
>>> #5 0x103ba9d5b in __wrap_dispatch_async_block_<wbr>invoke (/var/containers/Bundle/<wbr>Application/B3E557CA-5ED9-<wbr>4673-8B07-37A0F2DA472B/<<wbr>redacted>.app/Frameworks/<wbr>libclang_rt.asan_ios_dynamic.<wbr>dylib:arm64+0x4dd5b)<br>
>>> #6 0x105f1549b in _dispatch_call_block_and_<wbr>release (/usr/lib/system/<wbr>introspection/libdispatch.<wbr>dylib:arm64+0x149b)<br>
>>> #7 0x105f1545b in _dispatch_client_callout (/usr/lib/system/<wbr>introspection/libdispatch.<wbr>dylib:arm64+0x145b)<br>
>>> #8 0x105f1a04f in _dispatch_main_queue_callback_<wbr>4CF (/usr/lib/system/<wbr>introspection/libdispatch.<wbr>dylib:arm64+0x604f)<br>
>>> #9 0x181d43f1f in <redacted> (/System/Library/Frameworks/<wbr>CoreFoundation.framework/<wbr>CoreFoundation:arm64+0xe9f1f)<br>
>>> #10 0x181d41afb in <redacted> (/System/Library/Frameworks/<wbr>CoreFoundation.framework/<wbr>CoreFoundation:arm64+0xe7afb)<br>
>>> #11 0x181c622d7 in CFRunLoopRunSpecific (/System/Library/Frameworks/<wbr>CoreFoundation.framework/<wbr>CoreFoundation:arm64+0x82d7)<br>
>>> #12 0x183af3f83 in GSEventRunModal (/System/Library/<wbr>PrivateFrameworks/<wbr>GraphicsServices.framework/<wbr>GraphicsServices:arm64+0xaf83)<br>
>>> #13 0x18b20e87f in UIApplicationMain (/System/Library/Frameworks/<wbr>UIKit.framework/UIKit:arm64+<wbr>0x7387f)<br>
>>> #14 0x100122dc3 in main (<redacted>:arm64+0x1000aadc3)<br>
>>> #15 0x18178656b in <redacted> (/usr/lib/system/libdyld.<wbr>dylib:arm64+0x156b)<br>
>>><br>
>>> Address 0x00014d3ea224 is located in stack of thread T0 at offset 36 in frame<br>
>>> #0 0x10045cd57 in function signature specialization <Arg[0] = Owned To Guaranteed, Arg[1] = Owned To Guaranteed, Arg[2] = Owned To Guaranteed and Exploded> of closure #1 () -> () in <redacted>.imageDownloaded(<<wbr>redacted>.<wbr>DownloadImageRequest, index: Swift.Int) -> () (<redacted>:arm64+0x1003e4d57)<br>
>>><br>
>>> This frame has 4 object(s):<br>
>>> [32, 36) '' <== Memory access at offset 36 overflows this variable<br>
>>> [48, 208) ''<br>
>>> [272, 276) ''<br>
>>> [288, 448) ''<br>
>>> HINT: this may be a false positive if your program uses some custom stack unwind mechanism or swapcontext<br>
>>> (longjmp and C++ exceptions *are* supported)<br>
>>> SUMMARY: AddressSanitizer: stack-buffer-overflow (<redacted>:arm64+0x100e41a83) in <redacted>::addImage(void const*, int, int, int, float const*, float const*)<br>
>>> Shadow bytes around the buggy address:<br>
>>> 0x0001302dd3f0: f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5<br>
>>> 0x0001302dd400: f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5<br>
>>> 0x0001302dd410: f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5<br>
>>> 0x0001302dd420: f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5<br>
>>> 0x0001302dd430: f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5<br>
>>> =>0x0001302dd440: f1 f1 f1 f1[04]f2 00 00 00 00 00 00 00 00 00 00<br>
>>> 0x0001302dd450: 00 00 00 00 00 00 00 00 00 00 f2 f2 f2 f2 f2 f2<br>
>>> 0x0001302dd460: f2 f2 04 f2 00 00 00 00 00 00 00 00 00 00 00 00<br>
>>> 0x0001302dd470: 00 00 00 00 00 00 00 00 f3 f3 f3 f3 f3 f3 f3 f3<br>
>>> 0x0001302dd480: f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5<br>
>>> 0x0001302dd490: f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5 f5<br>
>>> Shadow byte legend (one shadow byte represents 8 application bytes):<br>
>>> Addressable: 00<br>
>>> Partially addressable: 01 02 03 04 05 06 07<br>
>>> Heap left redzone: fa<br>
>>> Freed heap region: fd<br>
>>> Stack left redzone: f1<br>
>>> Stack mid redzone: f2<br>
>>> Stack right redzone: f3<br>
>>> Stack after return: f5<br>
>>> Stack use after scope: f8<br>
>>> Global redzone: f9<br>
>>> Global init order: f6<br>
>>> Poisoned by user: f7<br>
>>> Container overflow: fc<br>
>>> Array cookie: ac<br>
>>> Intra object redzone: bb<br>
>>> ASan internal: fe<br>
>>> Left alloca redzone: ca<br>
>>> Right alloca redzone: cb<br>
>>><br>
>>><br>
>>><br>
>>> So, how do I properly go back and forth between C and Swift code with pointers to arrays of floats?<br>
>>><br>
>>> Thanks,<br>
>>><br>
>>> --<br>
>>> Rick Mann<br>
>>> <a href="mailto:rmann@latencyzero.com">rmann@latencyzero.com</a><br>
>>><br>
>>><br>
>>> ______________________________<wbr>_________________<br>
>>> swift-users mailing list<br>
>>> <a href="mailto:swift-users@swift.org">swift-users@swift.org</a><br>
>>> <a href="https://lists.swift.org/mailman/listinfo/swift-users" rel="noreferrer" target="_blank">https://lists.swift.org/<wbr>mailman/listinfo/swift-users</a><br>
>><br>
>> ______________________________<wbr>_________________<br>
>> swift-users mailing list<br>
>> <a href="mailto:swift-users@swift.org">swift-users@swift.org</a><br>
>> <a href="https://lists.swift.org/mailman/listinfo/swift-users" rel="noreferrer" target="_blank">https://lists.swift.org/<wbr>mailman/listinfo/swift-users</a><br>
><br>
<br>
______________________________<wbr>_________________<br>
swift-users mailing list<br>
<a href="mailto:swift-users@swift.org">swift-users@swift.org</a><br>
<a href="https://lists.swift.org/mailman/listinfo/swift-users" rel="noreferrer" target="_blank">https://lists.swift.org/<wbr>mailman/listinfo/swift-users</a><br>
</div></div></blockquote></div><br></div>