如何在 Genie 中使用 Sqlite.Callback

How to use Sqlite.Callback in Genie

在尝试解决问题 时,我发现我可以尝试调用 PrintSingleRecipe 作为来自 Database.exec 的回调。但是,似乎回调不能是常规函数,它们有一些我在互联网上似乎找不到的 属性。

我是这样称呼的:

else if response is "3" //Show a Recipe
    res:string = UserInterface.raw_input("Select a recipe -> ")
    sql:string = "SELECT * FROM Recipes WHERE pkID = %res"
    db.exec(sql, PrintSingleRecipe, null)

函数本身如下所示:

def PrintSingleRecipe(n_columns:int, values:array of string, column_names:array of string)
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    for i:int = 0 to n_columns
        stdout.printf ("%s = %s\n", column_names[i], values[i])
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "Ingredient list"
    print " "
    stdout.printf("%-5s", "%03i" )

但是,我在编译时遇到以下错误:

valac --pkg sqlite3 --pkg gee-0.8 cookbook.gs
cookbook.gs:42.26-42.42: error: Argument 2: Cannot convert from `PrintSingleRecipe' to `Sqlite.Callback?'
            db.exec(sql, PrintSingleRecipe, null)
                         ^^^^^^^^^^^^^^^^^
Compilation failed: 1 error(s), 0 warning(s)

如何正确运行精灵中的回调?

当函数作为参数传递时,Vala 编译器会对函数进行类型检查。当以这种方式使用函数时,它被称为 "delegate"。具体来说,Vala 编译器将检查函数的签名是否与委托类型定义的签名相匹配。函数的签名由其参数类型和 return 类型组成。 Cannot convert from 'PrintSingleRecipe' to 'Sqlite.Callback?' 表示 PrintSingleRecipe 函数的签名与 Sqlite.Callback 委托定义的签名不匹配。

Sqlite.Callback 委托定义如下所示: http://valadoc.org/#!api=sqlite3/Sqlite.Callback 您已经正确地确定所需的参数是 int, array of string, array of string,但您还需要包括 return 类型。在本例中,它是 int。所以你的回调应该是这样的:

def PrintSingleRecipe(n_columns:int, 
        values:array of string, 
        column_names:array of string
        ):int
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    for i:int = 0 to n_columns
        stdout.printf ("%s = %s\n", column_names[i], values[i])
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "Ingredient list"
    print " "
    stdout.printf("%-5s", "%03i" )
    return 0

返回非零值将中止查询。参见 https://www.sqlite.org/capi3ref.html#sqlite3_exec