Shared common definitions across C/C++ (unmanaged) and managed C# code

大城市里の小女人 提交于 2019-12-10 20:53:46

问题


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:


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.




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/1947576/shared-common-definitions-across-c-c-unmanaged-and-managed-c-sharp-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!