C# bindings for MEEP (Photonic Simulation Package) - c#

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.

Related

C# talking to C++ library - AAF SDK

I'm trying to read AAF files (that describe edited video and audio sequences) in c#. AAF is open source, and there's a C++ SDK available http://sourceforge.net/projects/aaf/.
I'm a C# coder and while I understand some of the C++ coding paradigms, my C++ is basically non-existent.
I presume the intereaction is possible using pinvoke which I've used before for interacting with Win32. With win32 I've pulled calling information from pinvoke.net, but I'm not entirely sure how I go about defining the pinvoke entry points from scratch with a third party SDK.
Can anyone help me to get started on this? For instance, what are the first steps in pinvoking a third party C++ library? Are there tools for helping automate this process?
You have basically two ways of doing that:
Using C++ Interop (implicit PInvoke)
Visual C++ can interop with native C++ code. So you can use Visual C++ as a bridge between the native C++ and C#. Basically you have to write wrapper (or "proxy") classes in visual C++ to interact with your native C++ objects.
Under the hood, this method uses PInvoke (therefore "implicit PInvoke") with specific options, but it has the advantage of retaining the object-oriented structure of the native C++.
Note that this method is not portable to Mono.
Using good ol' PInvoke
You can use PInvoke with C++ the exact same way as you use PInvoke with C.
There is however a limitation: you cannot PInvoke C++ methods this way, so you lose the C++ object-oriented structure.
If the library that you are using provides a C API, you can use that. Otherwise, you have to create a small C++ wrapper that will wrap the C++ API in the form of C-style free functions.
If you have a lot of classes to wrap this way, you can use SWIG to wrap automatically. As a bonus, SWIG recreates the object-oriented structure in C# via some guru code generation. However using SWIG requires some setup and I don't think it is necessary if you only need a few functions.

How to use a C++ project from within a .NET application?

I'm a regular .NET developer aiming to integrate a C++ library into a .NET project. I have a few ideas, but since I'm new to C++ in general I don't know the limits of the technology I'm trying to work with. The C++ project is essentially a fast sound renderer that can playback multi-track audio files with a bunch of different postprocessing tricks. All of this is cool, but considering I have a simple .NET WinForms app I want to integrate with, things start to look messy.
Firstly, the C++ project has no .NET bindings or ActiveX/COM integration. Its a plain 'ol MS VC++ 9 project. If I am to work with the project in my .NET app I'll have to somehow interface with it, ie. create class instances, set properties, call methods, marshal data in and out, etc.
Secondly, its built to run as an independent Windows app and manages its own windows using the MS Windows API. This is fine, but somehow I need the .NET VM running in the background, managing the show and running all my C# code. I don't write C++ so I need to stick with C# to build an app around this lib.
Thirdly, whether I'm running in the same process as the C++ lib or not, I need a way to build/interface/debug these 2 separate apps as if they were one. I have no background in C++ programming except for the fact that I have written a couple C++ DLLs for high-performance data manipulation.
So, many questions and no idea how to start!
I can fully compile this lib and get it into a VC EXE, but how do I co-compile my .NET code into it? Or alternatively, how do I compile the C++ code into the .NET EXE so it runs within a managed environment? Note that it wasn't designed for this and may misbehave if I attempt to change too much.
The main problem is interfacing with it. How do I expose some C++ classes to be accessed from .NET? I know exactly which classes I need and I'll need only a couple dozen classes along with their relevant methods/properties to be available from .NET. I don't mind handwriting wrapper classes in .NET to help the .NET VM understand the class structure of the bytes transferred back and forth. I'm hoping I can directly work with C++ objects from a managed environment so most of my code can remain in .NET.
Even if I run it as an independant app, would I have to resort to sockets or something to communicate with it? This is the absolute worse case and I'll do anything to avoid this.
Any help or pointers are appreciated, I hope I made myself and my task at hand clear and that my questions are specific enough and answerable. Thanks for any help!
Edit: If I write wrapper classes or generate them, can I use P/Invoke to create class instances and call methods on them and have them run native C++ code in the background? Where will the memory for such C++ objects be stored and managed? Within the .NET heap or outside it?
You can write managed C++ (C++/CLI) wrapper to unmanaged C++ code. It would be the most flexible solution. Basically, you write a .NET assembly in C++, the assembly exposes managed classes which call your unmanaged code. Then you can reference this assembly from your C# projects.
There is a very basic article how to do that: http://www.windowsdevcenter.com/pub/a/dotnet/2004/03/29/mcpp_part3.html
This might be helpful as well:
http://www.multicoreconsulting.co.uk/blog/c-snippets/how-to-call-unmanaged-cplusplus-from-csharp/
And MSDN article .NET Programming in Visual C++.
Option 1
If you intend to use unmanaged C++ objects, it is probably better to write a managed wrapper in C++/CLI that has the same interface as the class that it's wrapping, but has a managed constructor and destructor to clean up the unmanaged resources. In C++/CLI you create unmanaged objects just like C++ that you have to delete yourself, or you can create managed objects with the gcnew keyword. The .NET facing side of the wrapper would take managed objects. The Native facing side of the wrapper could operate on all of the unmanaged data types that you already have.
For example, consider the unmanaged class Frobber. In C++/CLI, you would create a class called ManagedFrobber that would have all of the same methods as Frobber and contains a private instance of a Frobber. In the ManagedFrobber constructor, you would create your private Frobber instance. In the ManagedFrobber destructor, you would delete your private Frobber instance. Every method in your managed wrapper class would simply call methods on the private Frobber instance.
Option 2
If all you intend to call from the C++ world are c-style functions (static in the C# sense I guess), then P/Invoke is probably the way to go because then you don't have to worry about all of the nuances of a wrapper class. For example, if you pass an array from the Managed world into the Unmanaged world using a wrapper class, you have to worry about things like pinning the array in place so it doesn't get moved around by the .NET runtime while the managed world is messing around with it. With P/Invoke most of these nuances are handled for you.

Converting C++ solution to a class library

this might be a simple question, but as I have zero experience in C++ and my boss has given me a C++ solution work with I need to ask this question.
I have a C++ solution that needs to be turned into a .NET class library which can then be used in another .NET solution done in C#.
Is this even possible???
Cheers
You have to wrap all C++ classes that should be visible in .NET in C++/CLI classes.
Read this
There are also some automated tools to do this, but I never used these (I don't really trust them). Depends on how many C++ classes do you have, and how complex they are. Writing the wrappers is mostly straight-forward once you get used to some oddities of C++/CLI.
It depends of the output of the C++ solution. Is it an application (*.exe) or a library (*.dll)?
If it is a library (*.dll) you can use Platform Invoke Tutorial to call its functions out of managed code. A lot of examples of calling Win32 native functions can be found at http://pinvoke.net/.
If your result is an application it could be possible, that it has a COM interface. In that case you could use the COM interop to communicate with your application.
Last but not least you could write with C++/CLI a managed wrapper around your C++ functionality. But this is a lot of work and has many pitfalls.

How to add a python binding to 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.

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.

Categories