2

I have a function in C that takes a pointer. I am trying to call it from Swift.

From Calling C function from Swift, (and personal experience), doing &var does not work.

However, I am not able to cast &var into UnsafeMutablePointer... nor any type of conversion (like assigning the address of var to another variable of type UnsafeMutablePointer)

(assume Type is an object)

Thanks

Sample code:

var zero = CreateCompressionSession(&session as UnsafeMutablePointer<Unmanaged<VTCompressionSession>?>, Int32(CVPixelBufferGetWidth(pixelBuffer)), Int32(CVPixelBufferGetHeight(pixelBuffer)))

while trying to get it to call:

int CreateCompressionSession(VTCompressionSessionRef* session, int width, int height) {
    OSStatus err = VTCompressionSessionCreate(NULL, width, height, kCMVideoCodecType_H264, NULL, NULL, NULL, (VTCompressionOutputCallback)vtCallback, NULL, session);
    NSLog(@"%d %p", (int)err, session);
    if (err == noErr) {
        return 0;
    } else {
        return err;
    }
}
Community
  • 1
  • 1
dcheng
  • 1,827
  • 1
  • 11
  • 20
  • Did you check out Apple's guide to working with C from Swift? https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithCAPIs.html and https://developer.apple.com/swift/blog/?id=6 – Code Different Jul 22 '15 at 01:52
  • 1
    Yeah, not sure if just me, but they used &var and it worked (though they are doing swift for swift functions? kinda strange...). But I get the error. Am I not reading something on those 2 docs? – dcheng Jul 22 '15 at 16:13

1 Answers1

0

Maybe the problematic behavior you encountered was due to an older version of Swift, but in my experience &var should actually work.

Make sure that CreateCompressionSession() and VTCompressionSessionRef (and whatever type it points to if it's a pointer type) are available to the Swift code via a C header included in the bridging header. See what the Swift signature is of CreateCompressionSession() as it is imported into Swift and how VTCompressionSessionRef is imported. Work in your Swift code in terms of the imported structures. You can write convenience wrappers around them if you wish.

See this question for some additional info: Swift converts C's uint64_t different than it uses its own UInt64 type

Here is also an article that might help: http://www.swiftprogrammer.info/callback_void.html

Sorry if this is not very helpful, since I'm not familiar with all the details of what you are trying to do, but hopefully this helps.

Community
  • 1
  • 1
Anatoli P
  • 4,791
  • 1
  • 18
  • 22