我想要一个用 Vala 编写的共享库,它被 Python 应用程序调用。
所以我创建了这个 Vala 库,其中包含两个对象,每个对象都有一个功能。
唯一的区别是 Bar 在构造函数中有一个参数,而 Foo 没有。
using GLib;
namespace VLibrary {
public class Foo : GLib.Object {
public Foo() {
stdout.printf("VALA:\tcreating object...");
}
public void printThis(string x) {
stdout.printf("print from vala: " +x +"\n");
}
}
public class Bar : GLib.Object {
public Bar(string parameter) {
stdout.printf("vala object created (with parameter)");
}
public void printThis(string x) {
stdout.printf("print from vala: "+x+"\n");
}
}
}
并使用 valac 将其编译为共享 (.so) 库。
Valac 还生成了一个 .vapi 和一个 .gir 文件。
我从 .gir 文件生成了一个 .typelib 文件。
然后我写了一个小的 Python 应用程序,它应该使用这个库。
在执行之前我必须设置两个环境变量让 python 知道在哪里可以找到类型库和库文件。
导出 LD_LIBRARY_PATH=.
export GI_TYPELIB_PATH=.
#!/usr/bin/env python
from gi.repository import VLibrary
# Works, but doesnt call the constructor
foo1 = VLibrary.Foo()
# Works
foo1.printThis("FOO !")
# Works, but doesnt call the constructor
bar1 = VLibrary.Bar()
# Works
bar1.printThis("BAR !")
# TypeError: GObject.__init__() takes exactly 0 arguments (1 given)
text = 'hello world'
bar2 = VLibrary.Bar(text)
bar3 = VLibrary.Bar('hello world')
创建 Foo 类型的对象(构造函数中没有参数)有效,但 Foo 构造函数(Vala 代码)中的打印语句未执行。
当我想创建一个 Bar 类型的对象时,我必须在构造函数中省略字符串,否则 Python 会提示构造函数没有接受参数(即使它应该接受一个参数!)
除此之外,这两个对象都可以正常工作。使用参数调用对象方法(两个对象)有效并正确打印所有内容。
谁能告诉我我做错了什么?
我似乎不可能从 Python 调用任何类型的 Vala 构造函数。
对象已创建,但未调用构造函数代码。
请您参考如下方法:
https://wiki.gnome.org/action/show/Projects/PyGObject/IntrospectionPorting#Constructors
或者,如果您愿意,可以使用 GObject-style construction在你的 Vala 代码中。
