Getting function pointers from specific files - c++

I have a lot (perhaps hundreds) of different c++ files. Each one contains 10 functions, all of them taking in an int and a double and returning an int.
So the pointer to one of these functions in one of these files would look like this:
int (*foo)(int, double);
And then I have a class, which contains 10 of these function pointers.
Is it possible to have the constructor of this class take in a file name of one of these c++ files, put that file's functions into its pointers, and be able to use the functions later?
Preferably it would work so that even if two functions from different files had the same name it would still work (the idea is that multiple programmers could submit different files into the list, and they might use the same names for their 10 functions), but if that's not possible I could figure out something to avoid that.
From what I've searched, I can't seem to find anything that lets you differentiate between files when choosing functions, and even if I were to concatenate the functions into one file, there's still the problem of trying to designate which 10 functions to pick (as they all have the same arguments).
Is there any way to do this? Is there any better solution that I'm just not thinking of?

Is there any way to do this? Is there any better solution that I'm
just not thinking of?
You could just use different namespaces for them I think ? I mean each group of 10 functions in their own namespace; that way they won't conflict any more.
Other than that, you could try some dlsym + dlopen weirdness (or their win32 counterparts). It's not something I would do though.

I believe you are describing a dynamic linking library (aka shared object in Linux-land).

To achieve what you ask literally, you can turn each C++ file into a dynamic library and in the library constructor register the set of functions in some global map using FILE string as a key or declare them static, and make sure each file has some static variable whose initializer triggers functions' registration in the same global map.
To implement the same using plugin approach you can do it the way similar to what I have done it here (just download plugin.tgz, article is not yet ready). Contents:
app.cc - application, loads all plugins' libraries
module.cc - a plugin class implementing a business interface
module_ifc.h and a "loadable" interface bootstrap_ifc.h
client.cc - a plugin implementing bootstrap_ifc.h and using
method from module.cc resolved at runtime
Each of your C++ files having the same set of function would have a class implementing abstract business interface (useful part, all your functions) and bootstrap interface (unified initialization part, will be used by plugin loader). Each such class would be put into a separate shared library that declares class instance constructor and destructor methods.
A simple class to work with shared libraries on Linux:
#include <dlfcn.h>
class library {
void* _handle;
public:
library(char const* path);
~library();
template <typename F> F func(char const* name);
};
library::library(char const* path) {
_handle = dlopen(path, RTLD_NOW);
if (!_handle) throw std::runtime_error(dlerror());
std::clog << "opened library " << path << ", handle=" << std::hex << _handle << std::dec << "\n";
}
library::~library() {
if (_handle) dlclose(_handle);
std::clog << "closed library, handle=" << std::hex << _handle << std::dec << "\n";
}
template <typename F> F library::func(char const* name) {
dlerror();
F func = reinterpret_cast<F>(dlsym(_handle, name));
const char *dlsym_error = dlerror();
if (dlsym_error) throw std::runtime_error(dlsym_error);
std::clog << "loaded symbol " << name << ", ptr=" << std::hex << ((void*)func) << std::dec << "\n";
return func;
}

Related

Questions about DefineClass and my attempted usage of it

I'm trying to create a class/inject a class inside a java process through injecting a DLL into the process and using JNI to interface with java.
I came across a function called DefineClass but i can't quite get it work how i expected it to, so i have a few questions about the parameters the functions take:
In my case, what do i pass as class loader?
It accepts a byte array and its length as the "content" of the class, what would be the correct way of getting these bytes?
Which parts of the class is to be included in the array of bytes? Do i include everything or strip away parts?
Everything i have tried so far has resulted in the function returning null, so I'm not sure where to begin looking. If anyone would include some example usage or important notes about the usage that would be amazing!
jobject defined = jni->DefineClass("ChatFormatting", NULL, reach_buf, 4132);
if (defined == nullptr) {
std::cout << "Defined is NULL." << std::endl;
} else {
std::cout << "Success!" << std::endl;
}
You can get only class name and its' member entries addresses are incorrect.
Before inject, you must change addresses of entries by injectee module address.

streamed variables as a function parameter in C++

When you stream variables to an output stream such as cout, type conversion is automatic. What I'm trying to figure out is how to do this via a function call, for example:
inline void DEBUG(ostream& s) // Don't know if this prototype is appropriate
{
cout << s;
}
main()
{
int i = 5;
DEBUG("The value is: " << i << endl); // This doesn't compile
DEBUG("The value is: " + i + endl); // Neither does this
}
I found similar questions on here, but they all involve passing the stream object as a parameter, whereas I'm trying to pass the "streamed data" to a function that already has the stream object, so it's the other way round. Is this even possible? I don't want to resort to explicit type conversions. I also found this question, but I really don't want to write a whole logger class if I can avoid it.
At the moment I'm implementing it as a macro, which works, but I'd rather use an inline function if possible.
#define DEBUG(s) (cout << s)
Of course it does not compile. There are many reasons for that.
First, Operator << is not defined for standard streams, and you are trying to do exactly that: stream stream into stream in your DEBUG(). (Pun intended).
Second, operator << is not defined for string literals, and you are trying to invoke it here:
"The value is: " << i
+ is not defined for literals either, by the way.
To achieve the semantic you want to see, you will have to start with the stream. String literal need to be converted to stream first, and than you can apply << to it. This is ONLY way to achieve what you want.
Edit:
Now since I understand the rationale, I can give a better answer. There are many ways how people are trying to segregate different levels of debugging uniformely, and there are several libraries aiming for that (log4cpp, boost.log to name just few). Before you start implementing your own logging, I would definitely suggest looking into those. There is much more to the good logging than just debug levels.
If, for any reason, you want to use your own homebrew, here are the couple of recepies you might explore:
Use your own logger class (one of the very rare examples, close to
the single one! where Singleton is appropriate). You can than set the
logging level in the beggining of your application, and than just
call Logger::debug() << ...
Enrich above solution with macros. The problem with functions is that, unlike macros, they loose context. So if you want to log file and line number of the logging invocation (and you usually do!), you might want to do LOG_DEBUG << ...; here LOG_DEBUG would expand into something like Logger::debug() << __FILE__ << ":" << __LINE__ << ....
Once you've done this, you will see that sometimes you call other functions inside the << chain. At this point you might realize that those functions would be called regardless of your debug level, and might think you do not want to call them when debugging is not enabled (something along the lines LOG_DEBUG << " Object now is " << object.serialize(); So you will want to enrich the LOG_DEBUG macro to not execute anything when debug level does not match.
And the saga continues... Ready to use the library?
Well, what (at least some) logging libraries would do is create a temporary proxy object that would act as a stream:
#include <iostream>
struct LoggerProxy {
LoggerProxy(const char* file, int line)
{
std::cout << "File " << file << ", line " << line << ": ";
}
template<typename T>
LoggerProxy& operator<<(T&& t)
{
std::cout << t;
return *this;
}
};
#define LOG_DEBUG LoggerProxy{__FILE__, __LINE__}
int main()
{
LOG_DEBUG << "Value is: " << 4;
}
You can do a lot of fancy stuff with this, such as debug level checks, output to different streams or multiple backends (such as simultaneous output to std::cout/cerr and log file) and many more.

Using a std::stringstream from static member function for simplicity

I need an interface to write short messages to a log file, the messages often contains multiple parts such as an identifier together with a value.
In order to do this I've created a class that handles a lot of minor stuff such as creating filenames with timestamps and so on, although I don't want to use a variable argument list (int nargs, ...), so I thought my best option was to pass a std::stringstream to the write function instead.
I want to be able to write these calls as one-liners and not having to create a std::stringstream every time I need to do this, therefore I created a static member function to return a stringstream object I could use with my write function, although for some reason it doesn't work.
MyClass.h
class MyClass {
public:
static std::stringstream& stream();
void write(std::ostream& datastream);
private:
static std::stringstream* _stringstream;
};
MyClass.cpp
std::stringstream* MyClass::_stringstream = new std::stringstream();
std::stringstream& MyClass::stream() {
MyClass::_stringstream->str(std::string());
return *MyClass::_stringstream;
}
void MyClass::write(std::string data) {
this->_fhandle << data << std::endl;
}
void MyClass::write(std::ostream& datastream) {
std::string data = dynamic_cast<std::ostringstream&>(datastream).str();
this->write(data);
}
main.cpp
MyClass* info = new MyClass();
info->write("Hello, world");
info->write(MyClass::stream() << "Lorem" << ", " << "ipsum");
info->write(MyClass::stream() << "dolor sit" << " amet");
The code compiles, but when executing the application I get a std::bad_cast exception...
That's because you are creating an std::stringstream, which
doesn't derive from an std::ostringstream. Just create an
std::ostringstream, and the bad_cast should disappear.
Having said that, reusing the std::ostringstream many times
like this is generally not a good idea; the iostream classes are
full of state, which will not be reset between each use. It's
better to create new instance each time. (The classical
solution for this sort of thing is to create a copiable wrapper
class, which forwards to an std::ostream. An instance of this
is returned by info->write(), so you can write info->write() << "Hello, world" ....)

Multiplatform way to determine if a dynamic library is present

I need to check if a dynamic library is present, so that later I can safely call functions that use this library.
Is there a multiplatform way to check this? I am targeting MS Windows 7 (VC++11) and Linux (g++).
To dynamically "use" a function from a shared library requires that the library isn't part of the executable file, so you will need to write code to load the library and then use the function. There may well be ways to to do that in a portable fashion, but I'm not aware of any code available to do that.
It isn't very hard code to write. As "steps", it involves the following:
Load the library given a name of a file (e.g. "xx", which is then translated to "xx.so" or "xx.dll" in the architecture specific code).
Find a function based on either index ("function number 1") or name ("function blah"), and return the address.
Repeat step 2 for all relevant functions.
When no longer needing the library, close it with the handle provided.
If step 1 fails, then your library isn't present (or otherwise "not going to work"), so you can't call functions in it...
Clearly, there are many ways to design an interface to provide this type of functionality, and exactly how you go about that would depend on what your actual problem setting is.
Edit:
To clarify the difference between using a DLL directly, and using one using dynamic loading from the code:
Imagine that this is our "shared.h", which defines the functions for the shared library
(There is probably some declspec(...) or exportsymbol or other such stuff in a real header, but I'll completely ignore that for now).
int func1();
char *func2(int x);
In a piece of code that directly uses the DLL, you'd just do:
#include <shared.h>
int main()
{
int x = func1();
char *str = func2(42);
cout << "x=" << x << " str=" << str << endl;
return 0;
}
Pretty straight forward, right?
When we use a shared library that is dynamically loaded by the code, it gets a fair bit more complex:
#include <shared.h>
typedef int (*ptrfunc1)();
typedef char * (*ptrfunc2)(int x);
int main()
{
SOMETYPE handle = loadlibrary("shared");
if (handle == ERROR_INDICATOR)
{
cerr << "Error: Couldn't load shared library 'shared'";
return 1;
}
ptrfunc1 pf1 = reinterpret_cast<ptrfunc1>(findfunc("func1"));
ptrfunc2 pf2 = reinterpret_cast<ptrfunc2>(findfunc("func2"));
int x = pf1();
char *str = pf2(42);
cout << "x=" << x << " str=" << str << endl;
return 0;
}
As you can see, the code suddenly got a lot more "messy". Never mind what hoops you have to jump through to find the constructor for a QObject, or worse, inherit from a QObject. In other words, if you are using Qt in your code, you are probably stuck with linking directly to "qt.lib" and your application WILL crash if a Qt environment isn't installed on the machine.
LoadLibrary calls should fail, then you can know if the dynamic library is present or not. Also with dynamic loading you get the function pointer from the dynamic library and if the pointer is null then the platform doesn't support that function on that platform.
On windows you have LoadLibrary API to load a dynamic lib. And GetProcAddress API to look up the desired function in that lib. If GetProcAddress returns NULL for that particular function that you are looking for that functionality is not present for that platform. You can log then and decide fallback.

How to keep track of call statistics? C++

I'm working on a project that delivers statistics to the user. I created a class called Dog,
And it has several functions. Speak, woof, run, fetch, etc.
I want to have a function that spits out how many times each function has been called. I'm also interested in the constructor calls and destructor calls as well.
I have a header file which defines all the functions, then a separate .cc file that implements them. My question is, is there a way to keep track of how many times each function is called?
I have a function called print that will fetch the "statistics" and then output them to standard output. I was considering using static integers as part of the class itself, declaring several integers to keep track of those things. I know the compiler will create a copy of the integer and initialize it to a minimum value, and then I'll increment the integers in the .cc functions.
I also thought about having static integers as a global variable in the .cc. Which way is easier? Or is there a better way to do this?
Any help is greatly appreciated!
Using static member variables is the way to go. However, the compiler will not "create a copy of the integer and initialize it to a minimum value"; you'll have to provide a definition for each one in the .cc file and initialize it to 0 there. (Things are a bit different if you're using C++11, but the basic idea is the same.)
There's no reason to use static global variables instead of static members.
foo.h:
class Foo {
static int countCtor_;
static int countDtor_;
static int countprint_:
Foo();
~Foo();
static void print();
};
foo.cc:
#include <iostream>
#include "foo.h"
int Foo::countCtor_ = 0;
int Foo::countDtor_ = 0;
int Foo::countprint_ = 0;
Foo::Foo() {
++countCtor_;
// Something here
}
Foo::~Foo() {
++countDtor_;
// Something here
}
void Foo::print() {
++countprint_;
std::cout << "Ctor: " << countCtor_ << "\n"
<< "Dtor: " << countDtor_ << "\n"
<< "print: " << countprint_ << "\n";
}
But if you've got a lot of functions, the repetition involved is a bit annoying—it's very easy to accidentally do ++countBar_ when you meant ++countBaz_ (especially if you copy and paste the boilerplate), so you may want something a bit fancier, such as a static map and a macro that increments counts[__FUNC__], so you can just use the exact same line in each function. Like this:
foo.h:
#include <map>
class Foo {
static std::map<const char*, int> counts_;
Foo();
~Foo();
void print();
};
foo.cc:
#include <iostream>
#include "foo.h"
std::map<const char *, int> Foo::counts_;
#define INC_COUNT_() do { ++counts_[__FUNC__]; } while (0)
Foo::Foo() {
INC_COUNT_();
// Something here
}
Foo::~Foo() {
INC_COUNT_();
// Something here
}
void Foo::print() {
INC_COUNT_();
for (std::map<const char *, int>::const_iterator it = counts_.begin();
it != counts_.end(); ++it) {
std::cout << it->first << ": " << it->second << "\n";
}
}
In the example code above, __FUNC__ is a placeholder. Unfortunately, there is no standard-compliant value you can use in its place. Most compilers have some subset of __func__, __FUNC__, __FUNCTION__, __FUNCSIG__, and __PRETTY_FUNCTION__. However, none of those are standard in C++03. C++11 does standardize __func__, but only as an "implementation-defined string", which isn't guaranteed to be useful, or even unique. On top of that, the values will be different on different compilers. Also, some of them may be macros rather than identifiers, to make things more fun.
If you want truly portable code, in C++11, you can use something like string(__func__) + ":" + STRINGIZE(__LINE__)—this will be somewhat ugly, but at least each function will have a unique name. And in C++03, there is no equivalent. If you just need "portable enough", consult the documentation for every compiler you use, or rely on something like autoconf.
Is there any reason you can't use standard profiling tools that will count these calls for you? Something like gprof?
Otherwise static integers would be the way to go.
Assuming you want these statistics tracked all the time in your program, you could use an unordered_map of your function names:
std::unordered_map<const char *, unsigned> stats;
void foo () {
// use __FUNCDNAME__ for MSVC
++stats[__PRETTY_FUNCTION__];
//...
}
The use of compiler specific function name specifiers is purposefully there to get the decorated function names. This is so that overloaded function names get counted as separate functions.
This technique allows you to add new functions easily without thinking about anything else, but there is a small additional cost if there are hash collisions (which can be remedied somewhat by sizing the stats map to be larger). There is no hash computed on the string, since the key is a pointer type, it just uses the pointer value itself as the hash.
If this is just one-off code for profiling, then you should first try to use the code profiling tools available on your platform.
You can put static locals inside the methods themselves, that seems cleaner since these variables aren't logically connected to the class so there's no reason to make them members.
Additionaly, you could have a macro to simplify the work. I normally don't recommend using macros, but this seems like an appropriate use:
#define DEFINE_COUNTER \
static int noCalls = 0; \
noCalls++;
void foo()
{
DEFINE_COUNTER
}
Use a library that implements the Observer Pattern or Method Call Interception. You can choose one from this list, or use something like Vitamin.