C++ Calling different functions by string name - c++

I am relatively new to C++ - I leanerd it some 6+ years ago, but have never really used it until some months ago.
What is the scenario:
Considerably large system with a lot of modules.
Desired Output:
Modules (namely X) "expose" certain functions to be called over network and have the result sent back to the caller (namely Y)
The caller Y doesn´t know any info about X, despite what was exposed by the library (function name and parameters).
The calling of function in X from the library will have to happen through a string received from Y - or a set of strings, as there will be parameters as well.
Ideally what I want to have is something as generic as possible with variable return/paramaters types, or some kind of type-erasure - owing to the fact that I don´t know which functions each module will want to expose. I reckon its quite utopic to get something like that running in C++. But hopefully with pre-determined possible return/parameter types, it is feasible. The communication is not a problem for now, what matters is what should be done in the module side.
Question:
Would it be possible to accomplish such thing using C++ and Boost ? I would be really greateful if someone could give me some guidelines - literature/tutorials/(pseudo)code examples and so on and so forth. I am ofc not expecting a full solution here.
Possible solution:
I am a little bit lost as to which "functionalities" of the languages I can/should use - mainly due to my restrictions in the project.
I thought about using Variadic Templates and found the question below, which really helps, the only problem is that Variadic Templates are not supported in VS2010.
Generic functor for functions with any argument list
After some extensive research in the Web, the closest answer I got was this:
map of pointers to functions of different return types and signatures
The scenario is pretty much the same. The difference, however, seems to me that the OP already knows beforehand the return/parameters the functions he will be using. Due to my low reputation (I just joined) I unfortunately cannot ask/comment anything there.
TBH I didn´t get that well how to accomplish what the selected answer explains.
Using maps is a way, but I would have to store objects which contains function pointers (as also answered in the question), but as it is possible to see in the provided code by the user, it does have some hard-coded stuff which I wasn´t desiring to have.
Further clarifications:
Yes, I am restricted to use C++ AND VS2010 SP1.
No, despite Boost, I cannot use any other 3rd library - it would be great to be able to use some Reflection libraries such as CPGF http://www.cpgf.org/ (even though I am not 100% sure if thats what I really need)
Minor Edit:
- Scripting language bindings (such as LUA) are indeed a way to go, yet I didn´t want to include it in the project.
I hope someone can shed light on this problem!
Thanking in advance for any input!

Looks like you're needed a little reflection module. For example we have a struct of method info such as:
struct argument_info {
std::string name;
std::string type;
std::string value;
}
struct method_info {
std::string method_name;
std::string return_type;
std::list<argument_info> arguments;
}
then compile a dll with all exported functions
extern"C" __declspec(dllexport) void f1(int a, int b){/*...*/}
extern"C" __declspec(dllexport) int f1(std::string a, int b, char* c){ return x; }
in the interpreter's code:
void call_function(method_info mi, argument_info& t_return)
{
/* let g_mi be a map, where key is a std::string name of the method and the
value is method_info struct */
if(!g_mi->find(mi.method_name))
throw MethodNotFindException
if(g_mi[mi.method_name].arguments.size() != mi.arguments.size())
throw InvalidArgumentsCountException;
for(int i = 0; i < g_mi[mi.method_name].arguments.size(); i++)
{
if(g_mi[mi.method_name].arguments[i].type != mi.arguments[i].type)
throw InvalidArgumentException;
}
t_return = module->call(mi.arguments);
}
I hope it may help you.

Related

List of member reflection in C++ [duplicate]

Is there a way to enumerate the members of a structure (struct | class) in C++ or C? I need to get the member name, type, and value. I've used the following sample code before on a small project where the variables were globally scoped. The problem I have now is that a set of values need to be copied from the GUI to an object, file, and VM environment. I could create another "poor man’s" reflection system or hopefully something better that I haven't thought of yet. Does anyone have any thoughts?
EDIT: I know C++ doesn't have reflection.
union variant_t {
unsigned int ui;
int i;
double d;
char* s;
};
struct pub_values_t {
const char* name;
union variant_t* addr;
char type; // 'I' is int; 'U' is unsigned int; 'D' is double; 'S' is string
};
#define pub_v(n,t) #n,(union variant_t*)&n,t
struct pub_values_t pub_values[] = {
pub_v(somemember, 'D'),
pub_v(somemember2, 'D'),
pub_v(somemember3, 'U'),
...
};
const int no_of_pub_vs = sizeof(pub_values) / sizeof(struct pub_values_t);
To state the obvious, there is no reflection in C or C++. Hence no reliable way of enumerating member variables (by default).
If you have control over your data structure, you could try a std::vector<boost::any> or a std::map<std::string, boost::any> then add all your member variables to the vector/map.
Of course, this means all your variables will likely be on the heap so there will be a performance hit with this approach. With the std::map approach, it means that you would have a kind of "poor man's" reflection.
You can specify your types in an intermediate file and generate C++ code from that, something like COM classes can be generated from idl files. The generated code provides reflection capabilities for those types.
I've done something similar two different ways for different projects:
a custom file parsed by a Ruby script to do the generation
define the types as C# types, use C#'s reflection to get all the information and generate C++ from this (sounds convoluted, but works surprisingly well, and writing the type definitions is quite similar to writing C++ definitions)
Boost has a ready to use Variant library that may fit your needs.
simplest way - switch to Objective-C OR Objective-C++. That languages have good introspection and are full-compatible with C/C++ sources.
also You can use m4/cog/... for simultaneous generation structure and his description from some meta-description.
It feels like you are constructing some sort of debugger. I think this should be doable if you make sure you generate pdb files while building your executable.
Not sure in what context you want to do this enumeration, but in your program you should be able to call functions from Microsofts dbghelp.dll to get type information from variables etc. (I'm assuming you are using windows, which might of course not be the case)
Hope this helps to get you a little bit further.
Cheers!
Since C++ does not have reflection builtin, you can only get the information be teaching separately your program about the struct content.
This can be either by generating your structure from a format that you can use after that to know the strcture information, or by parsing your .h file to extract the structure information.

Creating A Typedef In C++

What Searching I've Done:
Hello, so typedefs are a new topic to me, and I have already read a page about them. (http://en.cppreference.com/w/cpp/language/typedef) But that's the best information I could find, the only problem is because I have no idea how it's working enough, I'm unable to rework it and use it for my situation.
Also, for the heads up; I'm trying to create a type like the 'App' type that you write when creating a CLR Form in C++. (Visual Studio) The only difference is it will be used for a different reason, so don't copy the code from it please.
My Code:
#pragma once
class Application {
public:
typedef class App; // Runnable C++ object (TEST PLEASE DON'T JUDGE)
private:
void Run(App myApp) { // ERROR: incomplete type is not allowed
}
};
How You Can Help Me:
Explain what a typedef is used for. (Examples will work)
Explain in what type I should create the 'App' type. (Eg. Class, String, Int, etc.) Or explain in what other way I can do so.
You can also just create an example with comments explaining.
Thanks for the help! I tried to keep this question real explainable and sleek.
In C++, typedef simply creates an alias for another type, such that referencing the new type is identical to referencing the original type.
// create a alias for the int type
typedef int my_new_type;
// here a and b have the same type
int a = 1;
my_new_type b = 1;
The above is a contrived example, generally the types you use typedef for would be more complex (like std::vector<std::pair<int, std::string>>). For your use case, I'm not sure a typedef is what you are looking for.
I think you're looking for
typedef Application App;
But I'm not sure why you don't just do
class Application {
private:
void Run(Application myApp) {
}
};
As for usage, one use for typedef is to define types whose underlying type may vary depending on the build configuration, target platform and compiler. For example if you are writing a game that will run on PS4 and XBOX One, you might be using two different compilers depending on which platform you are building for.
#if defined(MSVC)
typedef __int64 TInt64;
#elif defined(GCC)
typedef int64_t TInt64;
#endif
This allows more of your code to be platform-agnostic and abstracts away compiler/platform details making app code more readable and encapsulating the assumptions we're interested in. It also reduces codebase size and preprocessing which can improve your compile times.
// We can assume this will be exactly 64 bits on all our target platforms.
TInt64 myInt = 0x1000000000000000;
P.S. Although it doesn't cover typedefs in general Marshall Cline's C++ FAQ is an great resource for beginners and experts alike.

Convert function template to function overload set

Assuming this is my library. And it is a very huge library:
library.hpp
template<class usertype> void function_name(usertype aaa)
{
}
This is my main
int main()
{
int x=3;
function_name(x);
double y=3.5;
function_name(y);
return 0;
}
I do not know what is going inside the library. What I want is to convert the library to adapt my code. In fact, reducing the template into real code.
I need the library code above be converted into:
void function_name(int aaa)
{
}
void function_name(double aaa)
{
}
So I can manipulate the library according to my needs instead of manipulating the general code that works for everybody. How can this conversion from template to real code be done (without manual effort, but in automatic way)?
Edit:
I want to convert the whole file library.hpp into library_2.hpp which contains no template. Instead with two real implemented functions. This is what happens in the middle of the compilation.
I am not looking for reducing the compilation time. I am dealing with a huge library made of 196 files. Among those many functions in the library, I will need a few of them related to my work. I intend to hack and extend this library. Extending the whole library has huge effort cost for me. I just want to extend only what I need. So, it is very important for me to reduce the code and simplify it and remove all templates replacing them with explicit code.
I am not good at C++ and it compiler errors. So, in such a huge library, I prefer to use automatic methods rather than involving manual code manipulation. I am also not good at understanding this library. To understand the library, better to convert its complicated functions into explicit implemented code related to what I really need. Then I can understand someones else code better. I will remove the functions not related to my needs. I also do not care about updates coming to the library. Once I establish new library, its maintenance is my duty. And the new library would be much smaller and easier for maintenance. Comments show that some people looking at my aim from different view. I hope this explanation is clear.
In case of curiosity, the library I am going to manipulate is odeint related to mathematical computations with rarely change or bug inside.
I'm not entirely sure what you want to achieve but from reading the comments, I think that your major concern is that you are trying to reduce compile times and get less template-related error messages. You are not trying to specialize library functions for your own types.
If you only instantiate the templated functions from the library with a handful of types, there is a simple recipe to get templates out of your picture. But it will force you to write two lines of code for each combination of templated function and type you want to use it with.
Create your own header file library_wrapper.hpp. There, you declare non-template versions of the functions you want to use.
library_wrapper.hpp
#ifndef LIBRARY_WRAPPER_H
#define LIBRARY_WRAPPER_H
#include <vector> // just an example
namespace library_wrapper
{
void
function_name(int);
void
function_name(double);
int
another_function(const std::vector<double>&, bool);
}
#endif
And then “implement” them once and for all using your so-little-loved template library.
library_wrapper.cpp
#include "library_wrapper.hpp"
#include <library.hpp> // the template library
namespace library_wrapper
{
void
function_name(const int arg1)
{
return library::function_name(arg1);
}
void
function_name(const double arg1)
{
return library::function_name(arg1);
}
int
another_function(const std::vector<double>& arg1, const bool arg2)
{
return library::function(arg1, arg2);
}
}
You compile library_wrapper.cpp once, fight the templates, and then continue using only your wrapper which provides the non-templated functions.
Be aware that this approach jeopardizes one of the major reasons templates can be so fast: inlining. Your wrapper functions cannot be inlined at compile-time because you are hiding their definitions from the compiler. This is on purpose and, on the other hand, buys you shorter compile times. Link-time inlining might give you some inlining back but you shouldn't take it as granted.
Note that this solution does not work quite as well with types (as opposed to functions). You could try writing some pimpl-wrappers but I don't recommend this. Maybe the best thing would be to become friends with your template library…
Update addressing your updated question
I am dealing with a huge library made of 196 files. Among those many functions in the library, I will need a few of them related to my work.
In case of curiosity, the library I am going to manipulate is odeint related to mathematical computations with rarely change or bug inside.
This seems like the above approach could indeed help.
Extending the whole library has huge effort cost for me. I just want to extend only what I need. So, it is very important for me to reduce the code and simplify it and remove all templates replacing them with explicit code.
I don't think that this is a good approach. Instead, use the library as a black box and build your own on top of it. Concentrate your developer effort on the new features and benefit from updates for the underlying library.
I assume that the library in question is free software (otherwise, what you want to do would be illegal anyway) and free software project should support each other. If you are building an awesome library Y on top of library X, both
projects, X and Y, can benefit. On the other hand, if you rip out only a part of that other library and add other functionality, your two rivalling projects might both end up as something incomplete and incompatible which is frustrating for both, you and your users.
To understand the library, better to convert its complicated functions into explicit implemented code related to what I really need. Then I can understand someones else code better.
I don't think that you can reasonably expect that some machine-generated code will be more readable than the original human-written code of the library. After all, human coders are taught to write code for humans but compilers are optimized for other aspects.
I am not good at C++ and it compiler errors. […] I am also not good at understanding this library.
I intend to hack and extend this library.
I also do not care about updates coming to the library. Once I establish new library, its maintenance is my duty.
I don't want to seem rude but … do you see the problem?
by specialization
template<>
void function_name(int aaa)
{
}
template<>
void function_name(double aaa)
{
}
sample code
#include <iostream>
template<class usertype>
void function_name(usertype aaa)
{
std::cout << "default\n";
}
template<>
void function_name(int aaa)
{
std::cout << "int value = " << aaa << '\n';
}
template<>
void function_name(double aaa)
{
std::cout << "double value = " << aaa << '\n';
}
int main()
{
int x = 3;
function_name(x);
double y = 3.5;
function_name(y);
struct Z{} z;
function_name(z);
return 0;
}

IOS code has become very slow because of objc_msgSend

I have rewritten part of my code from very simple c arrays to using (or trying to use) objects in order to get more structure into it. Instead of passing arrays through the function header I am now using a global array defined by a singleton. You can see an example of a function in my code below:
it was:
void calcdiv(int nx,int ny,float **u,float **v,
float **divu,float dx,float dy,float **p,
float dt,float rho, float **bp,float **lapp)
{
int i,j;
for (i=2;i<=nx-3;++i){
for (j=2;j<=ny-3;++j){
divu[i][j] = (u[i+1][j]-u[i-1][j])*facu +
(v[i][j+1]-v[i][j-1])*facv;
}
}
...
now it is:
void calcdiv()
{
int i,j;
SingletonClass* gV = [SingletonClass sharedInstance];
for (i=2;i<=gV.nx-3;++i){
for (j=2;j<=gV.ny-3;++j){
gV.divu[i][j] = (gV.u[i+1][j]-gV.u[i-1][j])*facu +
(gV.v[i][j+1]-gV.v[i][j-1])*facv;
}
}
...
Before the restructuring I have been using the function call as given above. That means passing the pointers to the arrays directly. Now I access the arrays by the singleton call "SingletonClass* gV...". It works very fine except the fact that it is much slower than before. The profiler tells me that my program spends 41% of the time with objc_msgSend which I have not had before.
From reading through the posts I have understood that this probably can happen when msgSend is called very often. This is then most likely the case here, because my program needs a lot of number crunching in order to display an animated flow with OpenGl.
This leads me to my question: What would you suggest? Should I stay with my simple C implementation or is there a rather simple way to accelerate the objective c version? Please be patient with me since I am new to objective c programming.
Any hints and recommendations are greatly appreciated! Thanks in advance.
If your straight C method works fine, and your Objective C method puts you at a disadvantage due to method calling, and you need the performance, then there's no reason not to use straight C. From looking at your code, I don't see any advantage to whatever "structure" you're adding, because the working code looks almost precisely the same. In other words, Obj-C doesn't buy you anything here, but straight C does, so go with what's best for your user, because in terms of maintainability and readability, there's no difference in the two implementations.

Executing certain code for every method call in C++

I have a C++ class I want to inspect. So, I would like to all methods print their parameters and the return, just before getting out.
The latter looks somewhat easy. If I do return() for everything, a macro
#define return(a) cout << (a) << endl; return (a)
would do it (might be wrong) if I padronize all returns to parenthesized (or whatever this may be called). If I want to take this out, just comment out the define.
However, printing inputs seems more difficult. Is there a way I can do it, using C++ structures or with a workaroud hack?
A few options come to mind:
Use a debugger.
Use the decorator pattern, as Space_C0wb0y suggested. However, this could be a lot of manual typing, since you'd have to duplicate all of the methods in the decorated class and add logging yourself. Maybe you could automate the creation of the decorator object by running doxygen on your class and then parsing its output...
Use aspect-oriented programming. (Logging, which is what you're wanting to do, is a common application of AOP.) Wikipedia lists a few AOP implementations for C++: AspectC++, XWeaver, and FeatureC++.
However, printing inputs seems more
difficult. Is there a way I can do it,
using C++ structures or with a
workaroud hack?
No.
Update: I'm going to lose some terseness in my answer by suggesting that you can probably achieve what you need by applying Design by Contract.
It sounds like you want to use a debugging utility to me. That will allow you to see all of the parameters that you want.
If you don't mind inserting some code by hand, you can create a class that:
logs entry to the method in the constructor
provides a method to dump arbitrary parameters
provides a method to record status
logs exit with recorded status in the destructor
The usage would look something like:
unsigned long long
factorial(unsigned long long n) {
Inspector inspect("factorial", __FILE__, __LINE__);
inspect.parameter("n", n);
if (n < 2) {
return inspect.result(1);
}
return inspect.result(n * fact(n-1));
}
Of course, you can write macros to declare the inspector and inspect the parameters. If you are working with a compiler that supports variable argument list macros, then you can get the result to look like:
unsigned long long
factorial(unsigned long long n) {
INJECT_INSPECTOR(n);
if (n < 2) {
return INSPECT_RETURN(1);
}
return INSPECT_RETURN(n * fact(n-1));
}
I'm not sure if you can get a cleaner solution without going to something like an AOP environment or some custom code generation tool.
If your methods are all virtual, you could use the decorator-pattern to achieve that in a very elegant way.
EDIT: From your comment above (you want the output for statistics) I conclude that you should definitely use the decorator-pattern. It is intended for this kind of stuff.
I would just use a logging library (or some macros) and insert manual logging calls. Unless your class has an inordinate number of methods, it's probably faster to get going with than developing and debugging more sophisticated solution.