EIGEN_MATRIXBASE_PLUGIN conflict with std::vector - eigen3

Failed to use EIGEN_MATRIXBASE_PLUGIN when add some user-defined function to Eigen::MatrixBase.
inline int minComponentId() const { int i; this->minCoeff(&i); return i; }//success
inline void vectorTest0() {std::vector<double> logic;}//success
inline void vectorTest1(std::vector<double> logic) {}//fail
I do this like the Eigen documentation.The first function and the second are success but the third calls std::vector error.
I think std::vector may conflict with StdVector.h of Eigen Libary.
But how to use std::vector in EIGEN_MATRIXBASE_PLUGIN case?

Related

Wrapping of function in the same file

I need your suggestion to wrap my existing function.
I am from testing team I need to write unit test cases, so I don't want to depend on original definition so trying to write my own definiton.
Following is the source code which should not be changed.
source.c:
#include <stdio.h>
const char *getObjectName (int *anObject);
void func()
{
int *p;
getObjectName(p);
}
const char *getObjectName (int *anObject)
{
printf("i am in original\n");
}
From the above code I want to wrap getObjectName() function so that I can give my own definition.
I have googled a lot and tried following methods but didn't work out:
Method 1. using ld --wrap method
Method 2. using -DINTERCEPT
Method 3. using function pointer
I cannot use above 3 methods because calling function and called function are in same file.
So please suggest me any other methods to write my own defintion for getObjectName().

C99: Dynamic dispatch in a static library

Say I am developing a Math library and I want it to be such that it will detect whether or not user's machine support SSE (and which version) and based on that, separate internal functions will be called for the same API function. I can think of three ways to implement that:
Have global function pointers in the library and let user call mathInit() in their source. When they do, figure out the hardware details and assign the function pointers to different functions.
Same, except instead of having global function pointers, put them in a struct which is returned by mathInit(). This way, user will have to call math.vec3Add(...) or similar.
Same as 1, but instead of having global pointers, make mathInit() a macro so that the function pointers will have local scope in user's main() function (and require mathInit() to be called from main()). It will be in a header, of course.
Is any of these methods preferable? Is there some other, better way?
This is largely opinion-based, IMHO.
And my opinion is, a math library should expose the least possible amount of details about its internal workings and should not require tricky function pointers or data structures or even macros to work with to the user code, if possible.
I'd go with (1) and assume you would completely hide the function pointers in your library, i.e. call them through an indirection in library code.
(3) is definitely the worst option, because it puts restrictions on the user code that are not directly obvious. It might also create non-obvious problems/observations when debugging user code.
(2) Is a pretty uncommon way to present a library and requires at least intermediate C fluency, and might put off non-expert C users.
You could also expose a hasSSEfunction along with SSE and non-SSE functions and leave the decision what to use to the user code. Not sure that would have any benefits over (1), though.
My suggestion will be compiling a separate unit for each instruction set (e.g. Xnosse.o Xsse3.o Xsse4.o, etc.) and use an automatic dispatcher for those. The user needs to get the best performance for his PC, and not care about the inside detailing.
Since you wrote your code runs in a library, you can make the dispatch decision on load time automatically by using an init function that will be called on library load. You can also make this decision run only the firsts time a function is actually called, this is for lazy binding.
Here is a code example (gcc only!)
Compilation units:
//Xnosse.c
void do_some_math_stuff_no_sse(int x, int y)
{
...do some sophisticated math stuff with no sse support
}
void do_some_other_math_stuff_no_sse(int x, int y)
{
...do some other sophisticated math stuff with no sse support
}
//Xsse3.c
void do_some_math_stuff_sse3(int x, int y)
{
...do some sophisticated math stuff with sse3 support
}
void do_some_other_math_stuff_sse3(int x, int y)
{
...do some other sophisticated math stuff with sse3 support
}
//Xsse4.c
void do_some_math_stuff_sse4(int x, int y)
{
...do some sophisticated math stuff with sse4 support
}
void do_some_other_math_stuff_sse4(int x, int y)
{
...do some other sophisticated math stuff with sse4 support
}
Now to the library:
//my_math.h
/* Following definitions are in my_math.c */
extern void (*do_some_math_stuff)(int x, int, y);
extern void (*do_some_other_math_stuff)(int x, int y);
//my_math.c
void not_set(int x, int y)
{
// If you don't want to use the constructor for any reason,
// say you want lazy binding, this will do the trick as our
// functions do_math_stuff and do_other_math_stuff are initialized
// to this one
setup();
}
void (*do_some_math_stuff)(int x, int, y) = not_set;
void (*do_some_other_math_stuff)(int x, int y) = not_set;
int detect_sse()
{
..Do runtime detection of sse version
}
/* The following function will be called when your library loads */
void __attribute__ ((constructor)) setup(void)
{
if (detect_sse() == 0)
{
do_some_math_stuff = do_some_math_stuff_no_sse;
do_some_other_math_stuff = do_some_other_math_stuff_no_sse;
}
else if (detect_sse() == 3)
{
do_some_math_stuff = do_some_math_stuff_sse3;
do_some_other_math_stuff = do_some_other_math_stuff_sse3;
}
else if (detect_sse() == 4)
{
do_some_math_stuff = do_some_math_stuff_sse4;
do_some_other_math_stuff = do_some_other_math_stuff_sse4;
}
}
If you want lazy binding, remove constructor decorater from setup and compile with:
gcc -Wall -shared -fPIC -o libmy_math.so my_math.c Xnosse.c Xsse3.c Xsse4.c
If you want the dynamic dispatcher to run when the library loads use the following additional parameters to gcc:
gcc -Wall -shared -Wl,-init,setup -fPIC -o libmy_math.so my_math.c Xnosse.c Xsse3.c Xsse4.c

Is it possible to exchange a C function implementation at run time?

I have implemented a facade pattern that uses C functions underneath and I would like to test it properly.
I do not really have control over these C functions. They are implemented in a header. Right now I #ifdef to use the real headers in production and my mock headers in tests. Is there a way in C to exchange the C functions at runtime by overwriting the C function address or something? I would like to get rid of the #ifdef in my code.
To expand on Bart's answer, consider the following trivial example.
#include <stdio.h>
#include <stdlib.h>
int (*functionPtr)(const char *format, ...);
int myPrintf(const char *fmt, ...)
{
char *tmpFmt = strdup(fmt);
int i;
for (i=0; i<strlen(tmpFmt); i++)
tmpFmt[i] = toupper(tmpFmt[i]);
// notice - we only print an upper case version of the format
// we totally disregard all but the first parameter to the function
printf(tmpFmt);
free(tmpFmt);
}
int main()
{
functionPtr = printf;
functionPtr("Hello world! - %d\n", 2013);
functionPtr = myPrintf;
functionPtr("Hello world! - %d\n", 2013);
return 0;
}
Output
Hello World! - 2013
HELLO WORLD! - %D
It is strange that you even need an ifdef-selected header. The code-to-test and your mocks should have the exact same function signatures in order to be a correct mock of the module-to-test. The only thing that then changes between a production-compilation and a test-compilation would be which .o files you give to the linker.
It is possible With Typemock Isolator++ without creating unnecessary new levels of indirection. It can be done inside the test without altering your production code. Consider the following example:
You have the Sum function in your code:
int Sum(int a, int b)
{
return a+b;
}
And you want to replace it with Sigma for your test:
int Sigma(int a, int b)
{
int sum = 0;
for( ; 0<a ; a--)
{
sum += b;
}
return sum;
}
In your test, mock Sum before using it:
WHEN_CALLED: call the method you want to fake.
ANY_VAL: specify the args values for which the mock will apply. in this case any 2 integers.
*DoStaticOrGlobalInstead: The alternative behavior you want for Sum.
In this example we call Sigma instead.
TEST_CLASS(C_Function_Tests)
{
public:
TEST_METHOD(Exchange_a_C_function_implementation_at_run_time_is_Possible)
{
void* context = NULL; //since Sum global it has no context
WHEN_CALLED(Sum (ANY_VAL(int), ANY_VAL(int))).DoStaticOrGlobalInstead(Sigma, context);
Assert::AreEqual(2, Sum(1,2));
}
};
*DoStaticOrGlobalInstead
It is possible to set other types of behaviors instead of calling an alternative method. You can throw an exception, return a value, ignore the method etc...
For instance:
TEST_METHOD(Alter_C_Function_Return_Value)
{
WHEN_CALLED(Sum (ANY_VAL(int), ANY_VAL(int))).Return(10);
Assert::AreEqual(10, Sum(1,2));
}
I don't think it's a good idea to overwrite functions at runtime. For one thing, the executable segment may be set as read-only and even if it wasn't you could end up stepping on another function's code if your assembly is too large.
I think you should create something like a function pointer collection for the one and the other set of implementations you want to use. Every time you want to call a function, you'll be calling from the selected function pointer collection. Having done that, you may also have proxy functions (that simply call from the selected set) to hide the function pointer syntax.

Generate two functions with C Preprocessor

I have a project, and a case where I have a few often-changed preprocessor #defines that control how it works--ex:
void myfunction(int num, mystruct* content) {
doSomethingTo(content);
//...
#ifdef FEATURE_X
feature_x(content);
#endif
}
This works fine, although it does have to be recompiled each time, so it's in the "stuff that has to be recompiled each time" file. I would like to push it into a [static] library instead. I'm ok with changing how it's called (already have a function pointer for picking myFunction), so I'd like that to turn into
void myfunction(int num, mystruct* content) {
doSomethingTo(content);
//...
}
void myfunction_featureX(int num, mystruct* content) {
doSomethingTo(content);
//...
feature_x(content);
}
I need to do this in a couple places, so using a separate library (one with and one without -D FEATURE_X) for each isn't an acceptable option. I could do it with copy/paste, but that results in code reuse that carries a risk of fixing a bug in one copy but not the other.
Have the featureX versions of functions call the mainline functions. In your example myfunction_featureX would call myfunction and then do its own thing.
Surely, this is the point at which you change the activation of Feature X from a compile time issue into a run-time issue:
void myfunction(int num, mystruct* content)
{
doSomethingTo(content);
//...
if (FeatureX_Enabled())
feature_x(content);
}
The FeatureX_Enabled() test might be a full function, or it might be simply test an appropriately scoped variable that is defined outside the function — a static variable in the file, or an external variable. This avoids having to futz with the function pointers; it's the same function called as now. Changing a table of function pointers is equivalent to changing a single variable — it involves changing the value of something stored outside the function to change the behaviour of the function.
Would it help if you put myfeature_x in a function table instead?
#include <stdio.h>
#include <string.h>
typedef struct {
int x,y;
} mystruct;
typedef void (*fn_ptr)(mystruct* content);
fn_ptr vtable[10];
#define FEATURE_X_INDEX 0
void feature_x(mystruct *content)
{
printf("y: %d\n", content->y);
}
void myfunction(int num, mystruct* content) {
printf("x: %d\n", content->x);
//...
if (vtable[FEATURE_X_INDEX]) {
vtable[FEATURE_X_INDEX](content);
}
}
int main(void)
{
bzero(vtable, sizeof(vtable));
mystruct s;
s.x = 1;
s.y = 2;
myfunction(0, &s);
if (1) {
//Of course you'd use a more sensible condition.
vtable[FEATURE_X_INDEX] = feature_x;
}
myfunction(0, &s);
return 0;
}
Output:
x: 1
x: 1
y: 2
Then all you need to do is populate the virtual function table with NULLs if that feature is not to be used, and with function pointers if it is to be used. This you can do from wherever you want - your static library for example.. or you can compile feature_x into a dynamic library, load it at runtime and if the loading succeeded populate the function table, and clear the table when the dynamically linked library is unloaded.
I think the only benefit this really gives you over Jonathan Leffler's method is that the code for feature_x doesn't actually need to be linked into the same binary as your other code. If all you need is a runtime switch to turn the feature on or off, a simple if statement should do the trick, as Jonathan Leffler suggested. (Incidentally, there's an if here, too - it checks the function table's content :) )

Can you run a function on initialization in c?

Is there an mechanism or trick to run a function when a program loads?
What I'm trying to achieve...
void foo(void)
{
}
register_function(foo);
but obviously register_function won't run.
so a trick in C++ is to use initialization to make a function run
something like
int throwaway = register_function(foo);
but that doesn't work in C. So I'm looking for a way around this using standard C (nothing platform / compiler specific )
If you are using GCC, you can do this with a constructor function attribute, eg:
#include <stdio.h>
void foo() __attribute__((constructor));
void foo() {
printf("Hello, world!\n");
}
int main() { return 0; }
There is no portable way to do this in C, however.
If you don't mind messing with your build system, though, you have more options. For example, you can:
#define CONSTRUCTOR_METHOD(methodname) /* null definition */
CONSTRUCTOR_METHOD(foo)
Now write a build script to search for instances of CONSTRUCTOR_METHOD, and paste a sequence of calls to them into a function in a generated .c file. Invoke the generated function at the start of main().
Standard C does not support such an operation. If you don't wish to use compiler specific features to do this, then your next best bet might be to create a global static flag that is initialized to false. Then whenever someone invokes one of your operations that require the function pointer to be registered, you check that flag. If it is false you register the function then set the flag to true. Subsequent calls then won't have to perform the registration. This is similar to the lazy instantiation used in the OO Singleton design pattern.
There is no standard way of doing this although gcc provides a constructor attribute for functions.
The usual way of ensuring some pre-setup has been done (other than a simple variable initialization to a compile time value) is to make sure that all functions requiring that pre-setup. In other words, something like:
static int initialized = 0;
static int x;
int returnX (void) {
if (!initialized) {
x = complicatedFunction();
initialized = 1;
}
return x;
}
This is best done in a separate library since it insulates you from the implementation.

Resources