How to use Swift to invoke the C interface on a Mac to develop a barcode application

Source: Internet
Author: User
Tags sprintf

Although Objective-c is still alive and well, Apple has shifted its focus to Swift. The future development of Mac and iOS will inevitably be based on Swift. Because Swift is relatively new, many SDKs do not yet have a swift version available. Here's how to use Swift to call C.

Reference original: How to Bridge C Code to Create Swift Barcode Reader on Mac

Xiao Ling

Translation: Yushulx

Software download
    • Dynamsoft Barcode SDK for Mac

    • Xcode 6.4

Mixed use of Swift and C

Apple offers an ebook using Swift with Cocoa and objective-c in ibooks. You can read interacting with C APIs on the Web page.

The swift and C type mapping relationships reference:

Implement 1D/2D barcode applications on your Mac using Swift and C

Use the shortcut key command+shift+n in Xcode to create a new project.

header files and dependent libraries are dragged directly into the project. Xcode is automatically associated.

Command+n Creates a C file that invokes the underlying C dynamic-link library (dynamsoft Barcode dylib).

When you're done, Xcode pops up with a hint:

After you confirm, Xcode automatically generates a bridge header file. Add the header file used by C:

#import "Native_lib.h"

Refer to the Online code sample of the Dynamsoft Barcode SDK for some modifications:

#include   "Native_lib.h"  int dbr_release_memory (pbarcoderesultarray paryresult) {     dbr_freebarcoderesults (&paryresult);     printf ("Game Over\n");     return 0;}  pbarcoderesultarray dbr_decodebarcodefile (Char* pszimagefile) {    //  parse command    __int64 llformat =  (OneD | Qr_code);      int imaxcount = 0x7fffffff;    int  iIndex = 0;    ReaderOptions ro = {0};     pbarcoderesultarray paryresult = null;    int iret = - 1;    char * psztemp = null;    char *  psztemp1 = null;    struct timeval begin, end;      if  (Null == pszimagefile)     {         printf ("the syntax of the command is incorrect.\n");         return null;    }     //  set license    dbr_initlicense ("A825E753D10C6CAC7C661140EC5ABEC3");      // read barcode    gettimeofday (&begin, NULL);     ro.llbarcodeformat = llformat;    ro.imaxbarcodesnumperpage  = imaxcount;    iret = dbr_decodefile (PszImageFile, &ro,  &paryresult);     gettimeofday (&end, null);      // Output barcode result    pszTemp =  (char*) malloc (4096);     if (IRET != DBR_OK)     {        sprintf ( psztemp,  "failed to read barcode: %s\r\n",  dbr_geterrorstring (IRet));         printf ("%s",  psztemp);         free (psztemp);        return null;     }     if  (paryresult->ibarcodecount == 0)      {        sprintf (psztemp,  "No barcode found.  total time spent: %.3f seconds.\r\n ",                  ((float) ((end.tv_sec * 1000 * 1000  +  END.TV_USEC)  -  (begin.tv_sec * 1000 * 1000 +  BEGIN.TV_USEC))/(1000 * 1000)));         printf ("%s",  psztemp);         dbr_freebarcoderesults (&paryresult);         return  0;    }     sprintf (psztemp,  "Total barcode (s)  found: %d. total time spent: %.3f seconds\r\n\r\n ", paryResult-> ibarcodecount,             ((float) ((end.tv_sec  * 1000 * 1000 +  END.TV_USEC)  -  (begin.tv_sec * 1000  * 1000 + BEGIN.TV_USEC))/(1000 * 1000));     printf ("%s"),  PSZTEMP);      return paryresult;}

Modify the resulting header file:

#ifndef __dbrconsole__native_lib__#define __dbrconsole__native_lib__ #include <stdio.h> #include <stdlib.h > #include <string.h> #include <sys/time.h> #include "if_dbr.h" Pbarcoderesultarray dbr_ Decodebarcodefile (char* fileName); int dbr_release_memory (Pbarcoderesultarray paryresult); const char * GETFORMATSTR (_ _int64 format); #endif/* Defined (__dbrconsole__native_lib__) */
Writing command-line tools with Swift

Convert a string in Swift to char *:

var file:string = "/applications/dynamsoft/barcode Reader 3.0 trial/images/allsupportedbarcodetypes.tif"//Barcode File//let nameptr = StrDup (Filepath.bridgetoobjectivec (). utf8string) var fileptr = StrDup (file.cstringusingencoding (nsutf8stringencoding)!) var filename:unsafemutablepointer<cchar> = Unsafemutablepointer (fileptr)

Commented out interface Bridgetoobjectivec is available in earlier versions of Swift. Xcode 6.4 has been removed.

Command line Get barcode result:

Var result : pbarcoderesultarray = dbr_decodebarcodefile (FileName)  free (FILEPTR)  println ("Total barcode: \ (String (Result.move (). ibarcodecount) \ n ...")  var count  = result.move () .ibarcodecountvar pbarcoderesult: pbarcoderesult = nilvar  Barcodeindex = 1 // print barcode recognition resultsfor i in  0..<int (count)  {    pbarcoderesult = result.move (). Ppbarcodes.advancedby (i). Move ()     println ("Barcode: \ (barcodeindex++)")      println ("Page: \ (String (Pbarcoderesult.move (). Ipagenum)")     var  Lformat: __int64 = pbarcoderesult.move (). llformat    var format =  string.fromcstring (Getformatstr (Lformat))     println ("Type: \ (format!)")     println ("VALUE:&NBsp;\ (String.fromcstring (Pbarcoderesult.move () pbarcodedata)!)     println ("...")  } // free c memorydbr_release_memory ( Result

Create cocoa apps with Swift

To create a button and text control in appdelegate.swift :

@IBOutlet weak var window:nswindow! @IBOutlet weak var btload:nsbutton! @IBOutlet weak var btread:nsbutton! @IBOutlet weak var text:nstextfield! @IBOutlet weak var filepath:nstextfield!

To create a button response function:

@IBAction  func onclick (Sender: nsbutton)  {         Var title = sender.title        switch (title)  {         case  "Load barcode file":             dispatch_async (Dispatch_get_main_queue ())  {                 self.openpanel ()             }             break        case  "read  Barcode ":             if  self.filepath.stringvalue ==  ""  {                 text.stringvalue =  "please add image path!"                 return             }        &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;PRINTLN ("Default:"  + self.filepath.stringvalue)    &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;VAR&NBSP;DBR&NBSP;=&NBSP;DBR ()              text.stringvalue = dbr.decodefile ( Self.filePath.stringValue)!            break         default:             break        }     }

To associate code and UI elements in Interface Builder:

To load a file using nsopenpanel :

Func openpanel ()  {        var openPanel =  Nsopenpanel ()         openPanel.allowsMultipleSelection =  false        openpanel.canchoosedirectories = false         openPanel.canCreateDirectories = false         openPanel.canChooseFiles = true         openPanel.beginWithCompletionHandler {  (Result)  -> Void in             if result ==  nsfilehandlingpanelokbutton {                 if let path = openpanel.url?. Path {                    self.filepath.stringvalue = path                 }             }        }      }

create dbr.swift for reading barcodes:

Import foundation class dbr {    func decodefile (file:  String)->string? {         var fileptr =  StrDup (file.cstringusingencoding (nsutf8stringencoding)!)         var fileName: UnsafeMutablePointer<CChar>  = unsafemutablepointer (fileptr)         var result  : pbarcoderesultarray = dbr_decodebarcodefile (FileName)           free (fileptr)          println ("Total  barcode: \ (String (Result.move (). ibarcodecount)) \ n ... ")           var count = result.move () .ibarcodecount         var barcodeindex = 1        var results: string =  ""         // print  barcode recognition results        for i in  0..<int (count)  {            var  Pbarcoderesult = result.move (). Ppbarcodes.advancedby (i). Move ()               results +=  "barcode: \ (barcodeindex++) \ n"              results +=  "Page: \ (String ( Pbarcoderesult.move (). Ipagenum) \ n "              var lformat: __int64 = pbarcoderesult.move () .llformat             var format = string.fromcstring (GETFORMATSTR (LFormat) )              results +=  "Type: \ (format!) \ n "            results += " value: \ (String.fromcstring (Pbarcoderesult.move (). Pbarcodedata)!) \ n "            results += " ... \ n "          }         / / free c memory        dbr_release_memory (Result)           return results    }}

Run the 1d/2d barcode application:

Source

Https://github.com/yushulx/swift-barcode-reader


How to use Swift to invoke the C interface on a Mac to develop a barcode application

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.