2010-06-14 98 views
0

这是一种跟进的Integration of C#, F#, IronPython and IronRuby如何从C#/ F#调用IronPython函数?

问题,以便使用C/C++从Python函数,SWIG是最简单的解决方案。 相反的方式,也可以使用Python C API,例如,如果我们有一个Python函数如下

 
def add(x,y): 
    return (x + 10*y) 

我们可以拿出在C包装如下使用这条巨蟒。

 
double Add(double a, double b) 
{ 
    PyObject *X, *Y, *pValue, *pArgs; 
    double res; 

    pArgs = PyTuple_New(2); 
    X = Py_BuildValue("d", a); 
    Y = Py_BuildValue("d", b); 

    PyTuple_SetItem(pArgs, 0, X); 
    PyTuple_SetItem(pArgs, 1, Y); 
    pValue = PyEval_CallObject(pFunc, pArgs); 
    res = PyFloat_AsDouble(pValue);  

    Py_DECREF(X); 
    Py_DECREF(Y); 
    Py_DECREF(pArgs); 
    return res; 
} 

IronPython/C#或甚至F#怎么样?

  • 如何从IronPython调用C#/ F#函数?或者,IronPython/C#中有什么SWIG等价工具?
  • 如何从C#/ F#中调用IronPython函数?我想我可以使用“engine.CreateScriptSourceFromString”或类似的,但我需要找到一种方法来调用IronPython函数看起来像一个C#/ F#函数,而不是写在字符串中的代码,但从文件中读取。
+0

这是什么问题?你链接的问题没有回答什么? – Brian 2010-06-14 16:20:08

+0

另见例如http://blogs.msdn.com/b/nickhodge/archive/2008/11/12/ironpython-f-parallel-async-a-kittehz-brekfst.aspx – Brian 2010-06-14 16:22:10

回答

5

你说'现在将代码写入字符串,但是从文件读取',所以确定,读取文件。

Python从F#:

let s = File.ReadAllLines("foo.py") 
let engine = Python.CreateEngine() 
let scriptSource = 
    engine.CreateScriptSourceFromString(s, SourceCodeKind.Statements) 
... 

F#在Python:

import clr 
clr.AddReferenceToFile("SomeFsLib.dll") 

我刚刚从这些在这个问题上的联系。还没有尝试过,但是,它很简单,我认为它“正常工作”。不知道你在问什么。

2

我阅读了上一个问题的一些答案。 Kevin链接的一篇文章回答了你的问题。它在Ruby上,所以也许你没有阅读它。我不太了解DLR,但我认为它的目的是使访问统一,所以相同的代码应该可以与Python协同工作。

无论如何,http://www.highoncoding.com/Articles/573_First_Look_at_the_IronRuby.aspx在C#中给出了一个.NET 4.0示例,它使用dynamic使interop变得非常简单。镜像你给C例程,并从Brian的代码下面就,:

//Brian's code goes here, but C#-ified with `var` instead of `let` 
engine.Execute(); 
object personClass = engine.Runtime.Globals.GetVariable("Person"); 
dynamic person = engine.Operations.CreateInstance(personClass); 
person.greet(); 

这是基于Ruby代码:

class Person 
    def greet() 
    puts 'hello world' 
    end 
end 

我想象相当于Python可以在完全相同的访问办法。我不知道你可以用DLR来做这件事,直到我阅读与你之前的问题相关的文章。 Interop在C#中非常容易,这非常令人兴奋。 (虽然我不想在F#中使用dynamic,因为F#代码给出了更加静态的感觉。)

1
pyEngine = Python.CreateEngine(); 
        pyScope = pyEngine.CreateScope(); 
        var instance = pyEngine.Execute(@" 
        def test(a,b): 
        return a+b 
        ", pyScope); 

        var test = pyScope.GetVariable<Func<int,int, int>>("test"); 
        int s = test(2,3); 
        MessageBox.Show(Convert.ToString(test)); 
        var ops = pyEngine.CreateOperations(pyScope);