我想要一个用 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 知道在哪里可以找到 typelib 和库文件。
导出LD_LIBRARY_PATH=。
导出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 构造函数中的 print 语句(Vala 代码)不会执行。
当我想创建 Bar 类型的对象时,我必须在构造函数中省略字符串,否则 Python 会提示构造函数不带参数(即使它应该带一个参数!)
除此之外,两个对象都按其应有的方式工作。使用参数调用对象方法(两个对象)可以正常工作并正确打印所有内容。
有人可以告诉我我做错了什么吗?
我似乎不可能从 Python 调用任何类型的 Vala 构造函数。
对象被创建,但没有调用构造函数代码。
最佳答案
https://wiki.gnome.org/action/show/Projects/PyGObject/IntrospectionPorting#Constructors
或者,如果您愿意,可以使用 GObject-style construction在您的 Vala 代码中。
关于python - 如何从 python 调用 vala 构造函数? (使用 GObject 自省(introspection)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23172624/