views:

83

answers:

3

Hi, I have a set of struct definitions that are used by both C# managed components and unmanaged C/C++ components. Right now, the identical struct definitions exist separately in C/C++ and C# code - causing duplication and related chaos. What's the best way to maintain single definitions that can be used from both C# and C/C++? Thanks! Amit

P.S.: I'm a C/C++ guy so if there's an obvious way to do this, I might be missing it completely!

+1  A: 

you need a IDL (interface definition language) try googling:

  1. protocol buffers.
  2. ICE (internet communication engine).
  3. Perhaps Microsoft COM ?.
  4. --edit: new entry -- it appears microsoft has an IDL compiler.

It all depends on what you want. all the above technologies have an IDL element to them, and come with their own set of baggage. I personally would stay low level C/C++ :D. So I would Google "Imatix GSL" and use the mentioned technology to model the problem in XML and generate the data structures in any programming language -- this technology is very simple and subtle and requires an experience programmer so if it doesn't make sense you should stick with an IDL.

-- edit: programming technique --

You can solve the problem by pure technique if you like. Chaos ensues when the rigor of engineering breaks down. If you make a decision to firewall and encapsulate the problem into pure C/C++ code you won't have to worry about the interface falling appart in your dependant code -- this is because any usefull language can interface with the ABI of your platform (simple C functions :P). The crux is not to expose internals, but just an interface with opaque types, such as numeric handles that represent objects and functions that may be performed on your types.

Hassan Syed
+3  A: 

I'm not familiar with your project(s), obviously, but have you considered building a managed bridge for your library in C++/CLI? With the "It Just Works" hackering the C++/CLI compiler does for you, many times you'll be able to marshal and share managed types with native code and back and forth.

Again, I don't know if it's right for you without more specifics, but it might be worth looking into.

Randolpho
+1  A: 

I once wanted to do so in one of my projects that had a hard separation between C# code and C code. Ideally, the C# code would have borrowed header files from the C code but:

  • since C# doesn't support include, I don't see how you could share the definition of a structure and include it both in your C# or C/C++ code
  • having my structure definitions in separate headers wasn't convenient anyway
  • I didn't want to rely on IDL or custom "parse the C headers and only extract structures definitions" preprocessing step
Gregory Pakosz