从Swift调用C函数

时间:2015-06-08 10:21:11

标签: ios objective-c c swift pointers

我试图从Swift调用一个C函数,但我不确切知道如何定义传递参数的变量。

功能c是:

Parse.initialize(this, "*******", "*******");

    ParsePush.subscribeInBackground("", new SaveCallback()
    {
        @Override
        public void done(ParseException e)
        {
            if (null == e)
            {
                ParseInstallation install = ParseInstallation.getCurrentInstallation();
                String token = install.getString("deviceToken");
                if (token != null)
                {
                    //saved it locally and other stuff
                }
                else
                 {
                   //saved a temporary default value locally
                 }
            }
        }
    });
    ParseInstallation.getCurrentInstallation().saveInBackground();

主要问题是DBFGetFieldInfo( DBFHandle psDBF, int iField, char * pszFieldName, int * pnWidth, int * pnDecimals ); pszFieldNamepnWidth inout参数。我试过了:

pnDecimals

但它给了我一个错误

var dbf:DBFHandle = DBFOpen(pszPath, "rb")
var fName:[CChar] = [] 
var fieldWidth:Int32 = 0
let fieldDecimals:Int32 = 0

let fieldInfo:DBFFieldType = DBFGetFieldInfo(dbf, i, fName, &fieldWidth, &fieldDecimals)

有什么想法吗?

3 个答案:

答案 0 :(得分:2)

UnsafeMutablePointer<Int8>, UnsafeMutablePointer<Int32>, UnsafeMutablePointer<Int32>

您需要将变量转换为方法签名所需的适当类型。

C语法:

  • const Type *
  • 输入*

Swift语法:

  • UnsafePointer
  • UnsafeMutablePointer

Apple在他们的使用Swift with Cocoa和Objective-C参考located here中涵盖了这一点。

答案 1 :(得分:0)

C语法-----&gt; Swift语法

const Type * -----&gt; UnsafePointer

输入* -----&gt; UnsafeMutablePointer

输入数量和类型应该相同

答案 2 :(得分:0)

要从字符串创建UnsafeMutablePointer<Int8>,请使用:

String(count: 10, repeatedValue: Character("\0")).withCString( { cString in
    println()
    // Call your function here with cString
})