views:

569

answers:

4

Is there an easy way to call Python objects from C#, that is without any COM mess?

+5  A: 

Yes, by hosting IronPython.

Daniel Earwicker
+4  A: 

In the current released version of C# there is no great way to achieve this without using some sort of bridge layer. You can host it IronPython to a degree but its hard to take advantage of the dynamic features of IronPython since C# is a very statically typed language

If you're speaking of IronPython though, C# 4.0 will be able to interop with that seemlessly. C# 4.0 is introducing a new feature calldh dynamic which allows it to work with any language running on the DLR.

dynamic d = GetSomePythonObject();
d.SomeMethod();
JaredPar
+1  A: 

You may take a look at this post.

Darin Dimitrov
+2  A: 

I know of 3 ways:

1) Use Iron Python, and your Python projects can interact freely with projects written in C#.

2) Expose your Python functions to COM. You would do this if you need to use Python libraries that you don't want to or can't convert to Iron Python (EG, if you just have a DLL.) The "COM mess" is not really so bad, if your Python code and C# code are running on the same machine. This code from this tutorial shows that it's not excessively ugly:

class PythonUtilities:
  _public_methods_ = [ 'SplitString' ]
  _reg_progid_ = "PythonDemos.Utilities"
  # NEVER copy the following ID
  # Use "print pythoncom.CreateGuid()" to make a new one.
  _reg_clsid_ = "{41E24E95-D45A-11D2-852C-204C4F4F5020}"

  def SplitString(self, val, item=None):
    import string
    if item != None: item = str(item)
    return string.split(str(val), item)

# Add code so that when this script is run by
# Python.exe, it self-registers.
if __name__=='__main__':
  print "Registering COM server..."
  import win32com.server.register
  win32com.server.register.UseCommandLine(PythonUtilities)

3) Have C# and Python communicate through sockets. You would do this if you have code you can't convert to Iron Python and you need to access it remotely. This requires the most work because you need to marshall and unmarshall the arguments and return values from bytes or strings, but it is what one team of mine did when we needed to make C# talk to a remote Python process.

RossFabricant