从 IronPython 调用 C# 对象方法

发布于 2024-08-25 14:07:12 字数 874 浏览 7 评论 0原文

我正在尝试在我的游戏中嵌入脚本引擎。由于我是用 C# 编写的,因此我认为 IronPython 非常适合,但我找到的示例全部集中在在 C# 中调用 IronPython 方法,而不是在 IronPython 脚本中调用 C# 方法。

让事情变得复杂的是,我在 Windows 7 64 位上使用 Visual Studio 2010 RC1。

IronRuby 的工作方式与我预期的一样,但我对 Ruby 或 Python 语法不太熟悉。

我正在做的事情:

        ScriptEngine engine = Python.CreateEngine();
        ScriptScope scope = engine.CreateScope();

        //Test class with a method that prints to the screen.
        scope.SetVariable("test", this); 

        ScriptSource source = 
          engine.CreateScriptSourceFromString("test.SayHello()", Microsoft.Scripting.SourceCodeKind.Statements);

        source.Execute(scope);

这会生成一个错误,“'TestClass'对象没有属性'SayHello'”

虽然使用“self.test.SayHello()”,但这个确切的设置在IronRuby中工作得很好,但

我对使用IronRuby持谨慎态度,因为它看起来不像 IronPython 那样成熟。如果足够接近,我可能会同意。

有什么想法吗?我知道这一定是简单的事情。

I'm trying to embed a scripting engine in my game. Since I'm writing it in C#, I figured IronPython would be a great fit, but the examples I've been able to find all focus on calling IronPython methods in C# instead of C# methods in IronPython scripts.

To complicate things, I'm using Visual Studio 2010 RC1 on Windows 7 64 bit.

IronRuby works like I expect it would, but I'm not very familiar with Ruby or Python syntax.

What I'm doing:

        ScriptEngine engine = Python.CreateEngine();
        ScriptScope scope = engine.CreateScope();

        //Test class with a method that prints to the screen.
        scope.SetVariable("test", this); 

        ScriptSource source = 
          engine.CreateScriptSourceFromString("test.SayHello()", Microsoft.Scripting.SourceCodeKind.Statements);

        source.Execute(scope);

This generates an error, "'TestClass' object has no attribute 'SayHello'"

This exact set up works fine with IronRuby though using "self.test.SayHello()"

I'm wary using IronRuby though because it doesn't appear as mature as IronPython. If it's close enough, I might go with that though.

Any ideas? I know this has to be something simple.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

じ违心 2024-09-01 14:07:12

我刚刚经历过这个……你没有发布所有代码,但我猜 SayHello 是公共的,这是正确的,但是包含 SayHello 函数的类也需要是公共的,以便 Python 可以看到它。

I've just had this... you don't publish all your code but I'd guess that SayHello is public which is correct, however the class containing the SayHello function also needs to be public so that Python can see it.

爺獨霸怡葒院 2024-09-01 14:07:12

这可能是因为您没有将类“test”声明为“public”以使其对 IronPython 可见。

It may have been because you did not declare your class "test" to be "public" to make it visible to IronPython.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文