Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice to partially change a C++ library while keeping the rest of the library intact

Tags:

c++

What is the best practice to add or modify a single class method in a well-established C++ library like OpenCV, while still reusing the remaining of the library code, preferably in the lib format.

At this point the only way I know is to copy all the source and header files that belong to the specific library (let's say OpenCV's core library) to the current source folder, modify that one function and recompile the module with the rest of the code. Ideally, I want to be able to link all the current .lib files the way they are, but simply define a new method (or modify a current method) for a class defined inside those libs in a way that my implementation of the method supersedes the implementation of the default library files.

Inheritance doesn't always seem to be an option, since sometimes the base class has private members that are required for the correct inherited class implementation.

like image 381
Bee Avatar asked Mar 26 '13 14:03

Bee


People also ask

Where C libraries are stored?

In Unix-like systems, the traditional place for the basic system libraries is /lib/ , with many additional libraries are found in /usr/lib/ , sometimes in sub-directories. Furthermore, locally built libraries are traditionally placed in /usr/local/lib/ .

Which three of the following are library functions?

Library functions include standard input/output (stdio. h), string manipulation (string. h), math functions (math.

What happens if standard library is not present in C?

But in pure C, with no extensions, and the standard library functions removed, you basically can't do anything other than read the command line arguments, do some work, and return a status code from main .


1 Answers

If the library is already compiled, there is not much you can do portably and cleanly.

If you know the specific target architecture the program will be runnning on, you could get the pointer to the member function and monkey patch the instructions with a jmp instruction to your own version of the method. If the method is virtual, you can modify the vtable. Those requires a lot of compiler-specific knowledge and would not be portable.

If the library ships in dynamic link archive, you could extract the archive and replace the method with your own version, and repack the archive.

Another method is you can copy the class' declaration from the header and add a friend declaration. Alternatively, you can do #define private public or #define private protected before including a header file. These will give you access to their private members.

With any of the above, you need to be careful that your changes does not modify the ABI of the library.

like image 122
Lie Ryan Avatar answered Oct 26 '22 07:10

Lie Ryan