C++ How to find class by it's name? - c++

How can I find a class to call it's methods by knowing class name and method names?
Details:
I'm trying to write library to replace some functions from another program which is also written using C++ by LD_PRELOAD functionality.
I need to have an ability to call functions from program in which this library gonna be integrated.

C++ loses all class naming information during the compile process!
You can`t do something like:
Class.forName("MyClass");
Like you know it from Java.
http://en.cppreference.com/w/cpp/language/class
This technique is called reflection and its not suported by C++
You can use a Framework (e.g. Boost) to help you out there, but the methods you want to call have to be declared and defined with this Framework.

C++ does not support reflection so you cannot search for functions/classes by name after compile time.
It sounds like if possible the design needs to be reworked. Ideally you should update the library to include what it needs from the programs. Either pull out the common logic from the programs into a third library - or put the functions that needs to be called by the programs into the current library and just pass the relevant data that will be manipulated into the library.
If this is not possible you can pass a function pointer from your programs into your library - this allows the library to have access to the functions it needs without any real knowledge of where it is coming from.
ie
void library_function1(std::function<void(int)> func)
{
func(1);
}

Related

c++ templates dependent on input from file

I have a complicated c++ scientific code, that uses multiple libraries.
Imagine that there are 5 different types of libraries, like linear solver, integration tool, etc. For each library type there are several different libraries that do exactly the same thing, but have different internal implementation. In fact, for every library a wrapper class is implemented, such that all libraries of the same type have exactly the same interface.
Now, I want to give this software to a user. I want user to be able to select the libraries they want to use after the code is already compiled. Currently it is done by means of an input file.
The only problem is coding this in the main program. When coding library selection, I end up using nested ifs, thus explicitly coding every possible combination of the libraries, conditioned on the parameters read from the file. I was wondering if there was a tidy way to do this.
You can't implement templates dependent in input from files, since template types are resolved in compilation, not runtime.
The tidy way to do this is by polymorphism (also, the elegant way ;D).
Define a Base class that defines the interface for each implementation, create the Children classes each one with it's own implementation, and then, (using input from file...or not... your call) resolve which algorithm to use by polymorphism.
:) Good luck.

Creating a dll without namespace for cpp

currently I am writing on a cpp-DLL. Afaik I have to put the functions into a class and a namespace if another cpp-program wants to use them. But I want to use the DLL with Labview too. Labview only recognizes the functions if they are free, e.g. neither in a namespace nor in a class. How can I implement this in my DLL? At the moment, I have set a #define-variable. If this variable is set, the functions are enclosed in a namespace and a class, if not, then they are free, but I have to compile the whole thing twice and I get two separate DLL files. So, what can I do if I only want one DLL file for both applications? (Please don't tell me to write the functions twice, the administrative outlay is even worse, I have tried this before).
Or do I simply have to call the DLL via LoadLibrary() when not using namespaces?
Thank you very much!
Afaik I have to put the functions into a class and a namespace if another cpp-program wants to use them.
This is plain wrong. You do not need to do this at all. On the contrary, DLL were originally introduced as libraries of C functions. C++ uses mangled names to represent namespace/class and types of parameters. There is no standard on this. Different compilers use their own scheme.
To summarize:
If you export simple C function from your dll, this will always work.
If you export classes or something from a namespace, this will
definitely work if other .exe/.dll is compiled with the same version of the
compiler. If not - this depends.
Regarding the LoadLibrary: it should be used when you do not know the name of the DLL or a name of the function in this DLL ahead or when you do not want to load this DLL at the beginning of your process. Otherwise (simple case) link your executable with implib for that DLL. This perfectly works for simple c-functions. LoadLibrary should be used when direct linking is not good for some reason.

Can C++ code reliably interact with other C++ code?

In C, I'm used to being able to write a shared library that can be called from any client code that wishes to use it simply by linking the library and including the related header files. However, I've read that C++'s ABI is simply too volatile and nonstandard to reliably call functions from other sources.
This would lead me to believe that creating truly shared libraries that are as universal as C's is impossible in C++, but real-world implementations seem to indicate otherwise. For example, Node.js exposes a very simple module system that allows plain C++ functions (without extern "C") to be exported dynamically using the NODE_SET_METHOD function.
Which elements of a C++ API are safe to expose, if any, and what are the common methods of allowing C++ code to interact with other pieces of C++ code? Is it possible to create shared libraries that can expose C++ classes? Or must these classes be individually recompiled for each program due to the inconsistent ABI?
Yes, C++ interop is difficult and filled with traps. Cold hard rules are that you must use the exact same compiler version with the exact same compiler settings to build the modules and ensure that they share the exact same CRT and standard C++ libraries. Breaking those rules tend to get you C++ classes that don't have the same layout on either end of the divide and trouble with memory management when one module allocates an object using a different allocator from the module that deletes the object. Problems that lead to very hard to diagnose runtime failure when code uses the wrong offset to access a class member and leaks memory or corrupts the heap.
Node.js avoids these problems by first of all not exporting anything. NODE_SET_METHOD() doesn't do what you think it does, it simply adds a symbol to the Javascript engine's symbol table, along with a function pointer that's called when the function is called in script. Furthermore, it is an open source project so building everything with the same compiler and runtime library isn't a problem.
This
For example, Node.js exposes a very simple module system that allows
plain C++ functions (without extern "C") to be exported dynamically
using the NODE_SET_METHOD function.
Is wrong, you can see that they are using an an extern "C" there in the init() function, which is clearly what node.js is calling which is then forwarding the function on to which ever C++ function they want, which isn't exposed.
As explained in this question How does an extern "C" declaration work? - When the compiler compiles the code, it mangles the function names, class names and namespace names. The reason it does this is because there can very easily be name clashes, for instance with overloaded functions.
Read about it more here: http://en.wikipedia.org/wiki/Name_mangling
The only way to refer and lookup a function is if the extern "C" declaration is used, which forces the compiler to not mangle the name. I.e. in the example above, the function init will be called init where as the function foo will be called something like _ugAGE (I made this up, because it doesn't matter, it isn't for human consumption)
In summary, you can expose any C++ to any other language, but the entry point to the library must be one or more extern "C"'d global functions as they are the only way to refer to an unmangled name.
Neither the C nor the C++ standards define an ABI. That is entirely left up to the implementation. The reason it's harder to get shared/dynamic libraries working for C++, is that C++ added things like classes, polymorphism, templates, exceptions, function overloading, STL, ...
So, the real source of information for you, is your compilers' documentation, as well as a corresponding set of guidelines for your library API to avoid any issues with any of the implementations your library will be built for. It's harder in C++ (the set of guidelines will likely be quite a bit bigger than for C, and you might have to work with a subset of C++), but not impossible.

Use a Qt library from a C application

Is there a way to write a qt library such that I can then use it (statically linked is fine) in a C application?
My C code is huge, old and will not convert to C++ without an inordinate amount of work. I say this as other similar questions seem to answer "just make your C code a Qt app". That's not an option.
I hope I can write a qt library, and build it in a way that lets it be called from C (something alluded to in QLibrary documentation).
The symbol must be exported as a C
function from the library for
resolve() to work. This means that the
function must be wrapped in an extern
"C" block if the library is compiled
with a C++ compiler. On Windows, this
also requires the use of a dllexport
macro; see resolve() for the details
of how this is done.
Can someone confirm/deny that I can do this, and let me know how much "qt" I can put in the library?
I don't need a GUI but would like to use some of the SQL handling.
Cheers
Mike
You can put as much Qt in a library as you wish, including full UI capability. The rub is that since you want to access it from C code, you must provide your own access functions and your C functionality will be constrained to whatever level of access you provide.
You can even pass Qt object pointers between C and C++ but you'll need to cast them into something that C can compile -- either void * or preferably your own new type definition (such as C_QString *). To C code these pointers will be opaque, but they'll still be valid.

Map existing C++ function to JNI

I have a library that I am compiling and creating a fully standalone C++ program. There are two cpp files, one that has the main, the other with all the functionality.
Currently, this program is implemented with a Java ProcessBuilder with args to call the C++ program and the results of that C++ program just simply go out to a file.
Now, I am wanting to get the results of that C++ function that does that work back to my java program. (The results in the C++ function is a double unsigned char array)
So my question is - is there a way to map those existing library functions so that I can call them from my java program directly, AND still keep using that library in the stand-alone way that I currently am, which is through that driver C++ program main()?
I am basically trying to avoid having to compile the same library twice - once for JNI functionality, and once as a standalone C++ program
Thanks
Java Native Access (JNA) will do what you want.
Java Native Interface (JNI) requires an additional layer of C glue between Java and C++. But JNA can access some C functions directly from Java.
You'll probably need to declare your function extern "C". You won't have to recompile the library, but you will have to link it with your C++ main function.
If you had a large C++ class library to expose, then you'd might be interested in SWIG. But for single C function, JNA is probably sufficient.
I think an exe can export functions similar to a dll (using __declspec(dllexport) on windows), which means you might be able to load it similarly to a jni-dll. (You might need to rename it .dll or .so to have java load it though.)
If loading doesn't work, another way would be to start your program in a separate process as you do now, but give it an command-line option which establishes some kind of shared-memory-area with the Java program.
That would avoid copying the daya back and forth, but might require a small utility DLL loaded by both the exe and the java program, i.e. not simpler. (Not sure if Java can setup shared-memory easily w/o native c calls ..)
(keeping answers separate for voting/comments/accept granularity)
Create a JNI wrapper DLL that runs the executable and returns the chars. Alternatively, compile the relevant code into a static library and link it either to a main() function for a standalone program, or to a JNI stub for calling from Java. In-process always better.
I believe a proper way to do it would be first to compile your functions into an independent dynamic library (.dll / .so / .dylib).
Then you can :
write a C++ executable that links against your shared library
write a Java program that binds to your C++ library thanks to BridJ, for instance (or JNA, if you stick to plain old C)