5

When you want to call C from python, you write a module like this:

http://docs.python.org/extending/extending.html

Now, I have a question:

I want to write a module for use in Python with C#.

How can I get C# to interact with native Python ?
(Note: I'm not interested in Python.NET or IronPython).

Stefan Steiger
  • 78,642
  • 66
  • 377
  • 442
  • 2
    Just out of curiosity, since both IronPython and Python.Net seem to fit the description of what you say you're looking for, why are you not interested in them? – Mia Clarke Oct 31 '10 at 22:21

1 Answers1

2

I know you are probably not gonna like this answer, but honestly: write it in C++, using boost::python or directly in Cython.

It'd be possible to write an extension using C#, but you'd have to convert the data structures used by Python, import a good deal of the Python C API, marshal everything back and forth between managed and unmanaged code, map object lifetimes between both Python's and C#'s garbage collector etc., which is most likely just not worth it.

You would also induce a dependency on the .NET framework, loose platform independence (probably even with Mono) while in general providing little benefit.

If you want to consume C# assemblies in CPython, your best bet actually is pywin32's win32com module on the Python side, and COM Interop on the .NET side. It allows you to expose your C# objects as COM classes with a few added attributes at the source level and easily import them into Python as objects, with events and everything. I had a lot of success integrating both platforms that way.

Jim Brissom
  • 31,821
  • 4
  • 39
  • 33
  • 1
    use managed C++ then it is easy to call your .net code (C#) from your C++ python binding. However you may still need to think about "pinning" objects to stop them being garbage collected when being used by the other side. – Ian Ringrose Nov 01 '10 at 09:22