How to dynamically load C++ function - c++

I have an C++ application, how can i load function from test.cpp function and execute it? I need a solution for Windows and Linux. I need this because my application users should change this function for their needs.
Thanks!

This is nearly impossible in pure c++. This is because you must compile your function first. When you have an object, ou can dynamically link it into you program, but this is not what you intend to do, i expect.
You might want to look at scripting languages like LUA etc that have well documented API's to be used in c++ (among others)
You can also deliver gcc with you application and call it from the application itself (exec..()) But this is quite heavy.

make this function in a shared library "dll or so"linux" " and then you can call it dynamically either using "extern " and library (.lib) or 'LibraryLoad (Windows) or dlopen (linux)" .. this is the way to do in c++ .. but you have to make your function call understood static from your program ..

Related

Load-time dynamic link library dispatching

I'd like my Windows application to be able to reference an extensive set of classes and functions wrapped inside a DLL, but I need to be able to guide the application into choosing the correct version of this DLL before it's loaded. I'm familiar with using dllexport / dllimport and generating import libraries to accomplish load-time dynamic linking, but I cannot seem to find any information on the interwebs with regard to possibly finding some kind of entry point function into the import library itself, so I can, specifically, use CPUID to detect the host CPU configuration, and make a decision to load a paricular DLL based on that information. Even more specifically, I'd like to build 2 versions of a DLL, one that is built with /ARCH:AVX and takes full advantage of SSE - AVX instructions, and another that assumes nothing is available newer than SSE2.
One requirement: Either the DLL must be linked at load-time, or there needs to be a super easy way of manually binding the functions referenced from outside the DLL, and there are many, mostly wrapped inside classes.
Bonus question: Since my libraries will be cross-platform, is there an equivalent for Linux based shared objects?
I recommend that you avoid dynamic resolution of your DLL from your executable if at all possible, since it is just going to make your life hard, especially since you have a lot of exposed interfaces and they are not pure C.
Possible Workaround
Create a "chooser" process that presents the necessary UI for deciding which DLL you need, or maybe it can even determine it automatically. Let that process move whatever DLL has been decided on into the standard location (and name) that your main executable is expecting. Then have the chooser process launch your main executable; it will pick up its DLL from your standard location without having to know which version of the DLL is there. No delay loading, no wonkiness, no extra coding; very easy.
If this just isn't an option for you, then here are your starting points for delay loading DLLs. Its a much rockier road.
Windows
LoadLibrary() to get the DLL in memory: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684175(v=vs.85).aspx
GetProcAddress() to get pointer to a function: https://msdn.microsoft.com/en-us/library/windows/desktop/ms683212(v=vs.85).aspx
OR possibly special delay-loaded DLL functionality using a custom helper function, although there are limitations and potential behavior changes.. never tried this myself: https://msdn.microsoft.com/en-us/library/151kt790.aspx (suggested by Igor Tandetnik and seems reasonable).
Linux
dlopen() to get the SO in memory: http://pubs.opengroup.org/onlinepubs/009695399/functions/dlopen.html
dladdr() to get pointer to a function: http://man7.org/linux/man-pages/man3/dladdr.3.html
To add to qexyn's answer, one can mimic delay loading on Linux by generating a small static stub library which would dlopen on first call to any of it's functions and then forward actual execution to shared library. Generation of such stub library can be automatically generated by custom project-specific script or Implib.so:
# Generate stub
$ implib-gen.py libxyz.so
# Link it instead of -lxyz
$ gcc myapp.c libxyz.tramp.S libxyz.init.c

DLL without exported functions?

I've snooped around a little bit in MS-Office DLLs, and I noticed that some of the DLLs don't have any exported functions. What I don't quite understand, how an application can use these DLLs without any functions exported ?!
I mean, the dllmain() does get executed on LoadLibrary(), but whats the point? Why would anyone create a DLL without exported functions?
thanks! :-)
One way of dealing with versions of a program destined for different languages is to put all of the resources into a language DLL. The DLL doesn't contain any code, just resources that have been translated to a target language. When the main program starts up, all it needs to do is load the proper language DLL.
I haven't looked at the DLLs in question; but it's possible in something like MSOffice Microsoft have done this to obfuscate the DLL to make it more difficult to debug / reverse engineer.
However, as you ask how would you use such a DLL? Well if the application knows the layout of the DLL then it can create a function pointer with the address of a known function and call it.
If you really want to dig further you could objdump the DLL and look for standard C / C++ ABI function prologues & epilogues and possibly work out where the functions start.
When you call LoadLibrary the DLL gets call of its DllMain.
That is DLL entry point. It is called on process attach and thread attach.
So you do have entry point.
As soon as it has at least one entry point then it can create instance of some interface (e.g. factory) an set it in e.g. TLS variables where other modules will pickup them.
So you can can have COM alike system of interfaces that are not exposed outside except to the application. Something like that - many over variations are possible.
Resources
The DLL likely has resources, like string tables, images, icons, etc., used by the rest of Office.
Always possible that they just don't export them as C interfaces. A DLL isn't magic, it's just bits and bytes, and nothing says that you can't get code out of a DLL if you don't ask Windows for it. I believe that .NET takes this approach- they save metadata in the DLL that tells the CLR what's in it, instead of making .NET functions available by the normal GetProcAddress approach. Unless you explicitly ask for it.

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)

Catching calls from a program in runtime and mapping them to other calls

A program usually depends on several libraries and might sometimes depend on other programs as well. I look at projects like Wine and think how do they figure out what calls a program is making?
In a Linux environment, what are the approaches used to know what calls an executable is making in runtime in order to catch and map them to other calls?
Any code snippets or references to resources for extra reading is greatly appreciated :)
On Linux you're looking for the LD_PRELOAD environment variable. This will load your libraries before any requested by the program. If you provide a function definition that matches one loaded by the target program then your version will be called instead.
You can't really detect what functions a program is calling however. You can however get all the functions in a shared library and implement all of those. You aren't really catching the functions, you are simply reimplementing them.
Projects like Wine do this in some cases, but not in all. They also rewrite some of the dynamic libraries. So when a Win32 loads some DLL it is actually loading the Wine version and not the native version. This is essentially the same concept of replacing the functions with your own.
Lookup LD_PRELOAD for more information.