开发者

What's the best practice for integrating C components into a C++ framework?

What's the best practice开发者_开发问答 for putting a C component into a C++ framework?

Our lab is building a C++ framework for our research. It uses some existing software as components. My job is to integrate software in C. The structure of the software is quite simple:

  • A set of extern variables in A.h
  • A set of data structures definitions and function prototypes in B.h.
  • The rest of the source code are .c files implementing the functions defined in B.h.


It's worth considering whether the style of client usage can usefully be improved using the additional features of C++. You can often trivially wrap C functions for a more C++-style experience. For example:

  • objects may be able to:
    • cleanly encapsulate data returned by some function calls that is then used as inputs to later calls, making its storage and usage more implicit
    • provide some guarantees about the correct sequencing of construction (initialisation), usage and destruction (clean-up)
  • namespaces can help group and disambiguate the identifiers
  • operator overloading can allow operations on types to be notated more like mathematical or logical expression, (e.g. x = a + b instead of x = add(a, b))
  • exceptions might reduce the number of places in the client code where error values have to be explicitly checked for and handled (useful if this error-related code is currently obfuscating the program logic)
  • if any of the functions implement generic functionality via void*s, then templates could be provided as a front end, automating the conversion to and from the void* type

This just off-the-top-of-my-head stuff... it's much easier to give concrete answers if you show a representative sample of the functions.

And of course, as you say you have the C source code, you can try compiling it with the C++ compiler, which would give you the option of avoiding "extern C" and a bit of the pollution of the global namespace, as well as adding much of the above not as wrappers but as tweaks to the existing code: may save you time and make maintainence easier.


Wrapping all the C header and source files with:

#ifdef __cplusplus
extern "C" {
#endif

//... rest of the file

#ifdef __cplusplus
}
#endif

This is compile and link properly in a c++ compiler. This is just an initial step. Depending on the implementation and how the functions are used in the C code, the c++ compiler may complain about few things. But try this as a your first step.

See here for a nice introduction on how to access C functions from C++.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜