在尝试解决问题How to print a sqlite table content with genie programming language时,我发现我可以尝试将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)
如何在Genie中正确运行回调?
答案 0 :(得分:1)
当函数作为参数传递时,Vala编译器会对函数进行类型检查。当以这种方式使用函数时,它被称为" delegate"。具体来说,Vala编译器将检查函数的签名是否与委托类型定义的签名匹配。函数的签名由其参数类型和返回类型组成。 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
,但您还需要包含返回类型。在这种情况下,它是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