How to add a python binding to C#? - c#

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).

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.

Related

C# Scripting inside Java

I know that I can use Lua Script files to manipulate Java Objects by using libraries like LuaJava. I had this idea of using C# scripts instead~
Is it possible to run C# scripts inside Java?
In theory, yes - you can certainly do this in .Net applications and there are Java / .Net interops.
Typically however Java / C# interops are performed through either P/Invoke or COM - both are pretty cumbersome for this sort of thing and so in reality this probably won't work as neatly as you might have imagined.
All the same if you did want to do this I'd probably recommend that you write the "scripting engine" (i.e. wrapper around the C# compiler) in C#, and then have that expose it to Java land via interops, for example:
public ScriptResult(string Script)
{
// Implemented in .Net
// Script is a string containing the C# code to execute
}
You then need to think carefully about how your C# scripts are going to be able to access any Java-land functionality, again I imagine the best way would be to implement a .Net wrapper class that calls Java objects through interops.
Using C# as a scripting language from within a .Net application is surprisingly straightforward - for information see:
Why You Should Use C# For Your Scripting Language
C# As a Scripting Language in your .NET Applications
Are C# programs "scripts"? Regardless, you could run most all outside programs from via Runtime.exec(...), but be sure to watch for traps: When Runtime.exec() won't.
Things get a bit more tricky if you wish to have two-way communication between C# and Java, which can be done via simple sockets/streams or all the way up to COM interfaces.
You can do it the other way around. Have a look at http://www.ikvm.net/ - it allows object/library reuse from one language in the other.

C# bindings for MEEP (Photonic Simulation Package)

Does anyone know of a way to call MIT's Meep simulation package from C# (probably Mono, god help me).
We're stuck with the #$#%#$^ CTL front-end, which is a productivity killer. Some other apps that we're integrating into our sim pipeline are in C# (.NET). I've seen a Python interface to Meep (light years ahead of CTL), but I'd like to keep the code we're developing as homogeneous as possible.
And, no, writing the rest of the tools in Python isn't an option. Why? Because we hates it. Stupid Bagginses. We hates it forever!
(In reality, the various app targets don't lend themselves to a Python implementation, and the talent pool I have available is far more productive with C#.)
Or, in a more SO-friendly question form:
Is there a convenient/possible way to link GNU C++ libraries into C# on Windows or Mono on Linux?
The straightforward and portable solution is to write a C++ wrapper for libmeep that exposes a C ABI (via extern "C" { ... }), then write a C# wrapper around this API using P/Invoke. This would be roughly equivalent to the Python Meep wrapper, AFAICT.
Of course, mapping C++ classes to C# classes via a flat C API is nontrivial - you're going to have to keep IntPtr handles for the C++ classes in your C# classes, properly implement the Dispose pattern, using GCHandles or a dictionary of IntPtrs to allow referential integrity when resurfacing C++ objects (if needed), etc. Subclassing C++ objects in C# and being able to overriding virtual methods gets really quite complicated.
There is a tool called SWIG that can do this automatically but the results will not be anywhere near as good as a hand-written wrapper.
If you restrict yourself to Windows/.NET, Microsoft has a superset of C++ called C++/CLI, which would enable you to write a wrapper in C++ that exports a .NET API directly.

Sharing objects between C# and C++ code

Is it possible to share references to C# objects between C# and C++ code without massive complexity? Or is this generally considered a bad idea?
The best solution for sharing a C# object between native and managed code is to use COM interop. This allows you to essentially share an interface of an object between managed code and it's equivalent signature in C++.
As for the complexity side of things. The majority of COM interop scenarios are straight forward and really are no more complex than good old COM programming. On the managed side it looks really no different than a normal interface.
Once you introduce multiple threads or start playing around between COM apartments though, things can get a bit tricky.
In my experience, the easiest way to get this working is the following.
Define an interface in C# that you wish to use in C++
Mark the interface with the ComVisible(true) attrbute
Run tlbexp on the assembly which generates a TLB file
Import the TLB into your native project
This will get the interface definition into both of your projects. How to pass that between the projects requires a bit more detail into your architecture.
Another solution I can recommend, from personal experience, is to use a managed C++ interface between the two if the C++ code you want to access is too large or too complex.
For example, I am using the RakNet C++ network library in a C# project. The solutions are to either create a massive wrapper class in C# to access the required C++ functions, create a C++ wrapper around those functions which can than be used as a COM interop or use Managed C++ (Visual C++/CLI).
I chose the latter which allows me to use C++ to access the RakNet library, but the classes created can be used directly in another .NET project as if. So the main logic has been created in those Managed C++ classes, which also allow me to use the .NET framework and some of its wonderful features. In my C# project I simply need to call the Managed C++ library which provides me with all in all 20 functions I need to perform everything.

C++ return values for Web Service

I have some .dll native C++ programs which mainly return int/double values, array structures and string values. These values should be taken by a Web Service program made in C#.
I would like to know if it is really necessary to modify my C++ programs and adapt to Web service, i.e. return values such as a XML string/file together with a XSD string,/file. Personally I think I should not modify them because I think C# can receive C++ values using interop and easily serialize using components of .Net library.
However, I would like to receive comments about the best, fast and effective way to pass C++ values to a Web Service.
Thanks!!
I think you can do it as you stated.
In the past, I achieved the same or similar by writing a C++/CLI wrapper around my native classes and consumed those from C#. This didn't incur the overhead of C# interop, which I've noticed can be quite expensive.
I think P/Invoke is what you want here. It will allow you to pass your simple and composite types between managed and unmanaged code, and you won't have to write any C++/CLI wrapper assemblies.
This (MSDN) is a good start for P/Invoke. If you scroll down here's a section called 'Specifying Custom Marshaling for User-Defined Structs'. This will allow you to pass your user-defined structs back and forth.
Look up MarshallAs and you can see all the primitive native types you can marshall. The DllImport attribute is something you will want to search for as well.
If performance becomes an issue, I would recommend serializing/deserializing into either named pipes or a local socket, but I'm not totally clear on the performance chararistics there. Good Luck!
The best, fastest, most efficient and effective way to expose your C++ application as a web service is to put C++ web service code on top of it.
See GSoap for a very fast, open source, implementation - one that is 3-5 times faster than the .NET and Java equivalents.
As long as you can return it to C#, C# should be able to return it from a web service. You should not have to do any manual serialization at all.
If you choose to go the serialization route you might want to look at 'thrift' (http://incubator.apache.org/thrift/).
From the website:
Thrift is a software framework for
scalable cross-language services
development. It combines a software
stack with a code generation engine to
build services that work efficiently
and seamlessly between C++, Java,
Python, PHP, Ruby, Erlang, Perl,
Haskell, C#, Cocoa, Smalltalk, and
OCaml.
Originally developed at Facebook,
Thrift was open sourced in April 2007
and entered the Apache Incubator in
May, 2008.

Is there a best practice for accessing C++ native COM functions to interop from C#?

Is there a best practice for accessing C++ native COM functions to interop from C#?
For example, if I have 100 C++ methods (basically a native library) that interacts with a core window component.
I want to basically make a wrapper for these C++ methods in C#, so all my newly hired employees can use that instead of C++, etc. The C++ code is legacy and scares me, so I want to deal with it just once. Is the approach here for each method to have a corresponding C# method? In fact, is there another way of doing this?
Can I have some sort of wrapper subsystem. How do you people generally do this?
Also, are there any performance considerations, etc.?
If your C++ methods are in a COM object, then you can use COM interop from C#. See CLR Inside Out: Introduction to COM Interop for a good introduction.
If those C++ methods are more like traditional API calls, then you'll want to use Platform Invoke (i.e. PInvoke). That entails creating managed prototypes in C# for the unmanaged (C++ functions). A good place to start is the Platform Invoke Tutorial.
As far as performance considerations go, there typically won't be much to worry about. Calling from C# might be fractionally slower than calling directly from C++, in large part due to marshaling data. Unless the code you're calling is in a critical loop, you're not going to notice any difference.
It really depends on what those native functions do. The more you have to share data between the unmanaged and managed worlds, the more difficult the process becomes. Without more information about your specific functions, it's difficult to say where you might encounter problems.
Use COM Interop to wrap the library. Then you can more or less treat the C++ code as .NET native code that can be called in the normal fashion.

Categories