Linux: C ++ Abstract Class as a Shared Object API

I read this article on C ++ DLL APIs. Will "C ++ mature approach: using an abstract interface" also work on linux with different compilers (exe and .so compiled with different compilers)? I couldn't find anything on the internet that confirms / denies it for Linux systems. In the article, the author says that it works for windows because COM technology works with other compilers.

To understand the question, please read at least the chapter "C ++ The Mature Approach".

+3


source to share


1 answer


Yes and no.

There is no guarantee that different compilers will execute the virtual implementation function in the returned interface class in the same way - and if so, then it would be disastrous (or powerless to mess up stuff ... even more fun). But if I call it correctly - modern g ++, clang and intel on linux seem to handle it the same way and therefore should interact at this level.

However, the article does not mention another article, and this applies to both linux and windows. If you take this approach, the only thing you can convey is

  • interfaces
  • simple types like int
  • Types in which you carefully control the location of memory.

This means that you do not have a function in your interface, for example void withVector(std::vector<int> v)

, since different standard compiler libraries may decompose the internal elements of a vector differently. In fact, this can change between compiler versions, standard library versions, and even with compiler settings.



So, you need to create IIntVector

one that wraps std::vector

and then uses withVector(IIntVector& v)

.

You may face the same problems if you pass or return any non-interface classes.

An old example, when this bit of me was passed boost::shared_ptr

between compilation units, where in one case the locking element was in the class, and in the other there was no lock - this means that the objects had different expected sizes and led to (silent) stack corruption. Fun for the entire development team.

I have found that it is less error prone to use a pure C bridge between two parties and provides a C ++ service layer that the creator and use of the DLL can use to create a pure C bridge. But even in C it's non-trivial.

In the case of C, you still need to watch for changes in data structures caused by compiler options (but they are less common), and you also need to be careful that one compiler does not add additions to your structures and the other does not.

+2


source







All Articles