是否可以从Python脚本向宿主应用程序返回对象或值?

2024-09-27 20:20:24 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,在Lua中,可以将以下行放在脚本的末尾:

return <some-value/object>

然后宿主应用程序可以检索返回的值/对象。在

我使用这个模式,以便脚本可以表示事件处理程序的工厂。然后使用基于脚本的事件处理程序来扩展应用程序。例如,宿主应用程序运行一个名为'SomeEventHandler.lua,它定义并返回一个对象,该对象是应用程序中“SomeEvent”的事件处理程序。在

这可以用Python实现吗?或者有更好的方法来实现这一点?在

更具体地说,我正在将IronPython嵌入到我的C应用程序中,并正在寻找一种方法来实例这些基于脚本的事件处理程序,从而允许使用Python扩展应用程序。在


Tags: 对象方法脚本应用程序处理程序returnobjectvalue
3条回答

这可以在Python中以同样的方式完成。您可以要求插件提供返回事件处理程序的getHandler()函数/方法:

class myPlugin(object):

  def doIt(self,event,*args):
    print "Doing important stuff"

  def getHandler(self,document):
    print "Initializing plugin"
    self._doc = document
    return doIt

当用户说“我想现在使用插件X”,你就知道该调用哪个函数了。如果插件不仅在直接命令后被调用,而且在某些事件(例如加载图形元素)上也被调用,那么您还可以为插件作者提供将处理程序绑定到这个事件的可能性。在

在嵌入Python时,这是完全可能的,也是一种常见的技术。This article显示了基础知识,this page也是如此。核心函数是PyObject_CallObject(),它从C调用用Python编写的代码

请参阅Embedding the Dynamic Language Runtime中的一些示例。在

一个简单的例子,setting-and-fetching-variables

SourceCodeKind st = SourceCodeKind.Statements;
string source = "print 'Hello World'";
script = eng.CreateScriptSourceFromString(source, st);
scope = eng.CreateScope();
script.Execute(scope);
// The namespace holds the variables that the code creates in the process of executing it.
int value = 3;
scope.SetVariable("name", value);

script.Execute(scope);

int result = scope.GetVariable<int>("name");

相关问题 更多 >

    热门问题