Calling C++ Code from C
If you’ve been doing this for any length of time, you may have noticed that nothing wants a C++ library. Apache, Lua, you name it, they all want a C library. Clearly nobody writes C++, right? Luckily, this is not true; you can make your C++ code look like C code, and nobody will be the wiser!
The trick is that when you make your library, you must use
extern "C" for the functions you are exposing. For instance, see this totally useful C++ function:
std::cout << "hello from c++!" << std::endl;
What kind of place would the world be if random C programmers couldn’t call this function? Luckily for the computer science community we’re here. Like Prometheus before us, we’ll steal this secret and bring it to the masses! The way to use this from C is to declare it in your header like so:
extern "C" void test_function(void);
You can also use this in blocks:
Meanwhile, in C…
Like all things in C, dynamically loading and using this code is tedious, but workable. First things first, we must ensure to
#include <dlfcn.h>. After this is done, you can get to work. First, you should create a void pointer for your library, and however many function pointers for your functions:
void * lib;
After that is done, you may open your library:
lib = dlopen("/path/to/libdmp_cpp_lib.so", RTLD_LAZY);
Next, we retrieve our symbols from the library. This will populate your function pointer:
test_func = dlsym(lib, "test_function");
After that is done, we can call our function:
Now that we’ve revolutionized software development, we should be sure to close our library handle. Leaking resources being bad and all…:
A Pattern Forming
Now, let’s compile our program and bask in the glory of our library!
main.c:20: undefined reference to `dlopen'
main.c:22: undefined reference to `dlsym'
main.c:26: undefined reference to `dlclose'
Now that we have that settled, let’s try this again…
hello from c++!