how to inject some code inside function.

  • Permalink
  • submit to reddit
  • Email
  • Follow


Hello. I have the following (simplified) code in the body of a
function:

if (myvar.get_type() == "int")
     dosomething<int> f(func);
     f(myvar.get());
else if (myvar.get_type() == "double")
    dosomething<double> f2(func);
    f(myvar.get());


What I would like to do is to be able to remove the ifs to be able to
inject code
inside this body but from outside the body of the function, maybe with
partial specializations,
but I don't know how to achieve this. Could anyone help me, please?


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply german 2/14/2009 4:50:42 PM

See related articles to this posting


On Feb 14, 5:50 pm, german diago <germandi...@gmail.com> wrote:
> Hello. I have the following (simplified) code in the body of a
> function:
>
> if (myvar.get_type() == "int")
>      dosomething<int> f(func);
>      f(myvar.get());
> else if (myvar.get_type() == "double")
>     dosomething<double> f2(func);
>     f(myvar.get());
>
> What I would like to do is to be able to remove the ifs to be able to
> inject code
> inside this body but from outside the body of the function, maybe with
> partial specializations,
> but I don't know how to achieve this. Could anyone help me, please?

You want to call a function on (or with) an object, and would like
the behavior of the function to be selected based on its type?

That's a virtual function.

Template specializations only work at compile time, but clearly your
code is deciding behavior at runtime.  If myvar's type isn't
polymorphic, either it should be, or it should hold a data member
that is that implements the functionality that is changeable.
You might also consider using the visitor pattern, but that's still
an elaboration on a virtual function solution.

If you don't use virtual functions, you'll end up simulating them (or
simulating something very much like them) in your own code, one way
or
another.  You might use templates to help write this simulation, but
I'm not sure how you could escape it entirely.  You might use a
lookup-
table, keyed by your type code, mapped to a function (polymorphic or
otherwise callable object (function pointer, binder, etc), but that's
still essentially a virtual function.

Chris


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply Chris 2/15/2009 7:35:57 AM

{ Top-posting is discouraged in this group. See the FAQ for posting guidelines. 
-mod }

You can overload the function.
Create the 2 identical functions with the same name, but with
different dummy argument types:

e.g. void function ( int ) {...} and void function ( double ) {...}

Depending on the actual argument passed in the function call, the
program will automatically choose which function to use.

I hope this is what your looking for, and sorry for the bad english.

On Feb 14, 7:50 pm, german diago <germandi...@gmail.com> wrote:
> Hello. I have the following (simplified) code in the body of a
> function:
>
> if (myvar.get_type() == "int")
>      dosomething<int> f(func);
>      f(myvar.get());
> else if (myvar.get_type() == "double")
>     dosomething<double> f2(func);
>     f(myvar.get());
>
> What I would like to do is to be able to remove the ifs to be able to
> inject code
> inside this body but from outside the body of the function, maybe with
> partial specializations,
> but I don't know how to achieve this. Could anyone help me, please?

{ Edits: quoted banner removed. -mod }


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply ISO 2/15/2009 7:37:59 AM

On 14 f�v, 23:50, german diago <germandi...@gmail.com> wrote:
> Hello. I have the following (simplified) code in the body of a
> function:
>
> if (myvar.get_type() == "int")
>      dosomething<int> f(func);
>      f(myvar.get());
> else if (myvar.get_type() == "double")
>     dosomething<double> f2(func);
>     f(myvar.get());
>
> What I would like to do is to be able to remove the ifs to be able to
> inject code
> inside this body but from outside the body of the function

template<typename F>
typename F::result_type visit(F f)
{
     if(myvar.get_type() == "int")
         return f(myvar.get<int>());
     if(myvar.get_type() == "double")
         return f(myvar.get<double>());

     assert(0);
}

Boost.Variant does that, in an even better way.
I recommend you use it.


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply Mathias 2/15/2009 7:41:02 AM

german diago wrote:
> Hello. I have the following (simplified) code in the body of a
> function:
> 
> if (myvar.get_type() == "int")
>      dosomething<int> f(func);
>      f(myvar.get());
> else if (myvar.get_type() == "double")
>     dosomething<double> f2(func);
>     f(myvar.get());
> 
> 
> What I would like to do is to be able to remove the ifs to be able to
> inject code
> inside this body but from outside the body of the function, maybe with
> partial specializations,
> but I don't know how to achieve this. Could anyone help me, please?
> 
> 

Obviously you think whatever the above is will be a solution to a
problem you have. Rather than ask us how to implement a solution you
would be better off telling us what problem you are trying to solve.

-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply Francis 2/15/2009 7:41:15 AM

On 15 feb, 14:41, Francis Glassborow
<francis.glassbo...@btinternet.com> wrote:
> german diago wrote:
> > Hello. I have the following (simplified) code in the body of a
> > function:
>
> > if (myvar.get_type() == "int")
> >      dosomething<int> f(func);
> >      f(myvar.get());
> > else if (myvar.get_type() == "double")
> >     dosomething<double> f2(func);
> >     f(myvar.get());
>
> > What I would like to do is to be able to remove the ifs to be able to
> > inject code
> > inside this body but from outside the body of the function, maybe with
> > partial specializations,
> > but I don't know how to achieve this. Could anyone help me, please?
>
> Obviously you think whatever the above is will be a solution to a
> problem you have. Rather than ask us how to implement a solution you
> would be better off telling us what problem you are trying to solve.
>
> --
>       [ Seehttp://www.gotw.ca/resources/clcm.htmfor info about ]
>       [ comp.lang.c++.moderated.    First time posters: Do this! ]

I think I explained myself in a very bad way, sorry. What I'm looking
for (if it's possible),
is a way to avoid this:

void operator()(value v1, ...)
     if (v1.get_type() == "int")
       dosomething<int>(f)
     else if...
}


I'm doing this because I want to do argument marshalling. For basic
types, this is not a problem.
The problem is that I want to register new types at runtime, and I'd
like them to be marshalled too.
I mean, using function call operator with this prototype:

void operator()(value v1, value v2, value v3);

  Where value holds any registered type in my type system,
I want to be able to add new types at runtime, for use with this kind
of function. And to use it, I must
do argument marshalling inside the function. Anyone knows how to do
this? It's being quite difficult for me.
Thanks in advance.


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply german 2/15/2009 6:08:41 PM

german diago wrote:
> On 15 feb, 14:41, Francis Glassborow
> <francis.glassbo...@btinternet.com> wrote:
>> german diago wrote:
>>> Hello. I have the following (simplified) code in the body of a
>>> function:
>>> if (myvar.get_type() == "int")
>>>      dosomething<int> f(func);
>>>      f(myvar.get());
>>> else if (myvar.get_type() == "double")
>>>     dosomething<double> f2(func);
>>>     f(myvar.get());
>>> What I would like to do is to be able to remove the ifs to be able to
>>> inject code
>>> inside this body but from outside the body of the function, maybe with
>>> partial specializations,
>>> but I don't know how to achieve this. Could anyone help me, please?
>> Obviously you think whatever the above is will be a solution to a
>> problem you have. Rather than ask us how to implement a solution you
>> would be better off telling us what problem you are trying to solve.

> 
> I think I explained myself in a very bad way, sorry. What I'm looking
> for (if it's possible),
> is a way to avoid this:
> 
> void operator()(value v1, ...)
>      if (v1.get_type() == "int")
>        dosomething<int>(f)
>      else if...
> }
> 
> 
> I'm doing this because I want to do argument marshalling. For basic
> types, this is not a problem.
> The problem is that I want to register new types at runtime, and I'd
> like them to be marshalled too.
OK now we know the problem.

> I mean, using function call operator with this prototype:
> 
> void operator()(value v1, value v2, value v3);

The first problem is that that must be a member function of some class.
The second problem is that you cannot add overloads or new template
specialisations at runtime.  C++ does not permit the creation of new
types at runtime so your type system must be effectively complete before
  execution of the program. I say effectively complete because there is
a little wriggle room to allow for dynamic libraries.

> 
>   Where value holds any registered type in my type system,
> I want to be able to add new types at runtime, for use with this kind
> of function. And to use it, I must
> do argument marshalling inside the function. Anyone knows how to do
> this? It's being quite difficult for me.

Given that the type must exist before translation has been completed I
think you need a member template. Something along the lines of:

class example {
public:
   template<typename parameter>
    void operator() (parameter p1, parameter p2, parameter p3);
// rest of definition
};

-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply Francis 2/16/2009 9:15:05 AM

On Feb 16, 2:08 am, german diago <germandi...@gmail.com> wrote:
> What I'm looking
> for (if it's possible),
> is a way to avoid this:
>
> void operator()(value v1, ...)
>      if (v1.get_type() == "int")
>        dosomething<int>(f)
>      else if...
>
> }
>
> I'm doing this because I want to do argument marshalling. For basic
> types, this is not a problem.
> The problem is that I want to register new types at runtime, and I'd
> like them to be marshalled too.
> I mean, using function call operator with this prototype:
>
> void operator()(value v1, value v2, value v3);
>
>   Where value holds any registered type in my type system,
> I want to be able to add new types at runtime, for use with this kind
> of function. And to use it, I must
> do argument marshalling inside the function. Anyone knows how to do
> this? It's being quite difficult for me.

With a map.

typedef std::map<std::string, boost::function<void()> > DispatchMap;
DispatchMap dispatchMap;

// fill the map as necessary

void operator()(value v1)
{
     DispatchMap::iterator f = dispatchMap.find(v1.get_type());
     if (f != dispatchMap.end())
         f(v1);
}

Yechezkel Mett


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply Yechezkel 2/16/2009 9:18:23 AM

Hi!

german diago schrieb:
> void operator()(value v1, ...)
>      if (v1.get_type() == "int")
>        dosomething<int>(f)
>      else if...
> }
> 
> 
> I'm doing this because I want to do argument marshalling. For basic
> types, this is not a problem.
> The problem is that I want to register new types at runtime, and I'd
> like them to be marshalled too.

You must either know all the types at compile time, or the new types
must implement marshalling themselves.

Something like:

void marshall(string type, value v)
{
	dosomething<type>(v);
}

will never be possible. You cannot invent new code at runtime.
(Theoretically at runtime you could automatically generate some code,
invoke the compiler to generate a shared object/DLL and load that DLL at
runtime. But you need the source code of the types in order to inspect
their members. And even then, you cannot automatically assign the
correct meaning to these members, whether they need to be marshalled or
not, or whatever)

Back to the problem:
I guess you want to marshall object, either to store them in a file or
database, or you want to marshall objects in order to transfer them over
network and then call a remote function with them.

First can be achived using for example Boost.Serialization:
http://www.boost.org/doc/libs/1_38_0/libs/serialization/doc/index.html

Second can be schived using for example ZeroC ICE:
http://www.zeroc.com/

I hope this helps.
Frank

-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply Frank 2/16/2009 4:21:46 PM
comp.lang.c++.moderated 10629 articles. 8 followers. Post

8 Replies
170 Views

Similar Articles

[PageSpeed] 20


  • Permalink
  • submit to reddit
  • Email
  • Follow


Reply:

Similar Artilces:

Injecting code into a function
Is there a general way of injecting code into a function, typically before and/or after the existing code ? I know that for most purposes, an OO solution, such as the template pattern, is a cleaner way to get the same effect, but it's not always applicable (e.g. if you have no control over the design and you are given a function to start with). In particular, I want to get access to the function's locals() just before it exits, i.e. something like: def analyzeLocals(func): func_locals = {} def probeFunc(): # insert func's code here sys._getframe(1).f_locals...

how to call a function inside the code
Hi, I have written a very simple function(in a file called stat.m) like function y = stat(x) y = x+5; When i want to call this function from another file like a = stat(5); a I get an error saying Input argument "x" is undefined. Error in ==> stat at 2 y = x+5; When i call the function from the command line, it is OK. However, this is not what i want. How can i call the stat function inside the code file? Thanks. On 12/31/2011 7:56 AM, Seyma wrote: > Hi, > > I have written a very simple function(in a file called stat.m) like > functi...

code inside a function invoked during static initialization
One can ivoke code during initialization of statics: // outside any function static bool do_something() { .... } static bool dummy = do_something(); Is there any possibility to invoke code that is *inside* a function, like: void foo() { .... DO_XYZ_DURING_STATIC_INITIALIZATION .... } I know what constructs bellow do (and when): void foo() { static int a = 1; static MyObject b(params); } and they do not fit for me. I am not aware of any trick but maybe there's something. (The reason for this all is that I would like to add documentation-like annotations near...

Why sfml does not play the file inside a function in this python code?
from tkinter import * import sfml window =3D Tk() window.minsize( 640, 480 ) def sonido(): file =3D sfml.Music.from_file('poco.ogg') file.play() test =3D Button ( window, text =3D 'Sound test', command=3Dsonido ) test.place ( x =3D 10, y =3D 60) window.mainloop() Using Windows 7, Python 3.3, sfml 1.3.0 library, the file it is played if i= put it out of the function. =BF what am i doing wrong ? Thanks. On 07/05/2013 10:27, cheirasacan@gmail.com wrote: > from tkinter import * > import sfml > > > window = Tk() > w...

Injected binary function code crashes remote application
Hi to all, I am injecting (using CreateRemoteThread) raw binary function code (complied in C++ with all security check functions removed) into a remote process. First I load complied binary function from a file then edit it in certain locations in memory which are addresses of function in a dll (got from GetProcAddress) which the binary function is supposed to call. It keeps on crashing the remote application, any ideas why this might have been? When Here is the assembly for the binary function code: PUSH EBP ; Start of function of...

It is acceptable to make function calls to your own code inside a spin lock?
Another question; function calls inside spin locks. Obviously, you can't call other people's functions inside your own spin lock because you have no idea what they might get up to. However, what about calling your own functions? The concern I have about doing this relates to the time spent inside the spin lock. Obviously, you wish to keep that as short as possible, and there is an overhead involved in making a function call. I'm not au fait with assembly language so it's only today that I've really been trying to find out exactly how much work is involv...

function inside a function
I have a question about the timing of function evaluations in this case: def function_a(x = 1) x**2 + x end def function_b(any_function) y = 4 + 5 #this would actually be more complex function_a(y) end puts function_b(function_a) I found that function_a(x = 1) is evaluated first, then function_b(function_a). I found that 'def function_a(x = nil) returns an error. Why does function_a need to be evaluated before it is called as an argument in function_b? PS - the reason I am writing things this way is to make function_b accept any function (within reason). -- Posted via http://ww...

function inside function
Hello, I have a problem. I want to define a function. And I want one of its input to be a function. This input will be a function but like a variable.For example,let like that, myfunc( func(a),b,c) b=5; c=func(b); now if i give sin(a) as input then func(b) will be sin(b) or if i give cos(b) as input then func(a) will be cos(b). (note:the functions will not be sin or cos.they will be more complicated which will be defined by me) Is such a thing possible?If it is possible, how will i do it? Thanks a lot. Best regards. This works for m...

Defining a function inside a function. Whats this feature ? How to use inside a class ?
[Note: parts of this message were removed to make it a legal post.] Hi Everyone, I am not sure if I have seen it being used earlier or probably I don't know how to use it. when I define function(s) inside a function within the main object, it works... def person def author p "I am author" end def reader p "I am reader" end end Now, if I call person.author # => I am author person.reader # => I am reader And it works fine with any hierarchy. The same thing doesn't seem to work inside a class. Any explanation ? Thanks! -- sur "is ...

Function Name from Inside the function
Is there a way to get a function name from inside the function during the execution time? One reason is that it would greatly aid debugging. To illustrate the concept, let's assume that the function names are stored in the list called $FunctionNames. Now, In[]:= Clear[f, g, h]; f[x_] := (Print[{Last[#], #} &[$FunctionNames]]; x^2) g[x_] := (Print[{Last[#], #} &[$FunctionNames]]; f[x] + 5) h[x_] := Module[{fname = Last[$FunctionNames]}, Print[{Last[#], #} &[$FunctionNames]]; If[MemberQ[debugSymbol...

Function declaration inside other function
Best explanation of my question will be an example, look below at this simple function: function SetEventHandler(element) { // some operations on element element.onclick = function(event) { // make something } } Everything works fine, but I'm not sure about one thing - will the onclick event handler be created in memory every time I call function SetEventHandler, or browser will create only one instance and use it for every element ? I can of course make that event handler as global function and assign only reference to onclick event, but I'm just won...

private functions inside a function
I recently inherited some older C code and saw something I haven't really seen before. I noticed it as it fails to compile at my home computer, as it has a newer (4.x vs 3.x ) gcc compiler. Its a private function, inside a function. Something like this. void myFunc(...) { static void myPrivateFunc(...) { } ... return; } I assume its failing to compile, because the private function is declared static. I guess what I'm comfused at is I havent' really seen functions declared in functions before. Could this have been done for performance reasons or something? The orig...

questions about functions inside a function
I want to create a list of function. Here is my code: In [9]: a = [] In [10]: for i in range(4): ....: b = lambda : i**2 ....: a.append(b) ....: ....: In [11]: for f in a: ....: f() ....: ....: 9 9 9 9 What I want is, the value of i should be bounded to the anonymous function. And the output should like this: for f in a: print f() 0 1 4 9 How to achieve this? Thanks a lot! Jeremy Sanders a �crit : > fdu.xiaojf@gmail.com wrote: > > >>What I want is, the value of i should be bounded to the anonymous >>function. And th...

Change function parameter from inside the function
Hi, Is there a way to change a parameter to a function in the body of the function? For instance, I have this function (defun add-to-population (rs1 population) (adjoin rs1 population :test #'equal) ) That I use this way (setq current-population (add-to-population result current-population)) But since I always use this same form (return a value, and then use setq to assign this return value to the function parameter), I would like to do this operation this way: (add-to-population result current-population) Basically, whatever is passed as the population argument should be assigne...

Is there a way to call function inside function......
hi Is there anyway to call function inside function parameter like this funcx(funcy()) thanks "Syed " <innocentlucifer@gmail.com> wrote in message <i8gkbj$a19$1@fred.mathworks.com>... > hi > > Is there anyway to call function inside function parameter like this > > funcx(funcy()) > > > thanks Yes, you can do this: x=1; y=funcx(funcy(x)); provided that you define the two functions. Ross "Ross W" <rosswoodskiwi@hotmail.com> wrote in message <i8gvp9$kjt$1@fred.mathworks.com>... > "...

Problem to evaluate a function inside a function
Dear everyone, I have defined a function chi2[��m_, ��_, ��_, data_] and when I compute chi2[0.27, -0.1, 0.1, data], it works well and I find 183.987. Now I try to find the minimum of this function by writting FindMinimum[chi2[��m, ��, ��, data], {{��m, 0.25, 0.30}, {��, -0.1, 0.2}, {��, 0.1, 0.2}}] and get the error message NDSolve::ndnum: Encountered non-numerical value for a derivative at z == 0.`. Apparently the problem is the folowwing: Inside my function chi2[��m_, ��_, ��_, data_] I have another function ePhip[��mp_, ��p_, ��p_] that I try to compute with ePhi = e...

How to print function with the code in the function body?
Hi, I try to use Dumper to print a hash which has a function ref as one of its value. But I only can get "sub { "DUMMY" }", which is not helpful for me to know what this function is. Is there a way to somehow print the function body? ~/linux/test/perl/library/Data/Dumper/Dumper$ cat main_fun.pl #!/usr/bin/perl use strict; use warnings; use Data::Dumper; sub f { return 0; } my %hash_of_arrays = ( a => \&f, ); print Dumper(\%hash_of_arrays); ~/linux/test/perl/library/Data/Dumper/Dumper$ ./main_fun.pl $VAR1 = { 'a...

Working with output of another function inside a function
Hi, I'm new to Matlab and programming as a whole so sorry about lack of terminology and clarity. I'll try my best to explain what my problem is. As the subject title says, I'm trying to work with the output of another function, say f1, inside a function f; but it doesn't seem to allow me to do it. I'm going to post my program, f , the error message and then the supporting function, f1 if that's OK: function findp(s,r,h,eps) S=solvecoupleat1(0,0,1,1,h,s); R=solvecoupleat1(0,0,1,1,h,r); if S*R>0 error('Error: This interval does not contain the ...

How to get the current function name inside a function?
Hi, In gnu C++, I can use __PRETTY_FUNCTION__ to get the function info inside a function. I'm wondering if it is possible to do the similar thing in matlab? Thanks, Peng In article <3f296615-8ab0-444b-813b-2093bd02f934@d45g2000hsc.googlegroups.com>, Peng Yu <PengYu.UT@gmail.com> wrote: >In gnu C++, I can use __PRETTY_FUNCTION__ to get the function info >inside a function. >I'm wondering if it is possible to do the similar thing in matlab? Try [ST,I] = dbstack; __PRETTY_FUNCTION__ = ST.name; -- "All human knowledge takes the form of interpretati...

Access DLL function via Function code
How can i access a specific function in a DLL from my Win32 Application referenced by an int Function ID. --- Win32 App - Call DLL functions DLL - contain lots of functions --- int FunctionID; 0 - Call Function_A, 1 - Call Function_B, ect. ExecuteFunction( int FunctionID ) { ... switch ( FunctionID ) { case 0: Function_A() case 1: Function_B() etc... } ... } Coding problem arise when i need to call a couple of hundreds of functions. *is the DLL needs to be modified? Also f...

included code inside class, code needed outside
In Router, in a method, in an included file is the controller code. In the model and in the view, I need access to the Controller's properties and methods. In Router, in an other method, I want to return a controller object to the model and the view. What now? Delirium tremens wrote: > In Router, in a method, in an included file is the controller code. In > the model and in the view, I need access to the Controller's > properties and methods. In Router, in an other method, I want to > return a controller object to the model and the view. What now? I'm not sure what yo...

MATLAB algorithm to MATLAB function code or C code
hallo firends, Can any body help me write this below code into MATLAB object oriented code or C code form please? M=50; % total number of periods. (choose for 1s duration) f0 = 50; % fundamental AC frequency T0 = 1/f0; %fundamental AC period T = M*T0; %Time for M periods (integer M) N=30; % sample points per period. dt = T0/N; % Sample at N points per period (integer N > 20) t = dt*[1:M*N-1]; % Sampling time array A0=120/2; % amplitude of AC signal. Divide by 2 or maybe sqrt (2) ? AC=A0*sin(f0*t*2*pi); % create AC signal. DC0=50; % DC amplitude DC=DC0*ones(1,le...

knowing the function arguments of a p-coded function file
Hi all, I have some function files which are .p so I cant see its contents. And each .p file calls few other .p files. I want to know what function arguments these .p files take and the order of their calls. How is it possible to know this ? Thanks Gopesh "gopesh patel" <patelgopesh@gmail.com> wrote in message news:49f26c30-14c3-4037-a525-024c5ea9664e@w1g2000vba.googlegroups.com... > Hi all, > > I have some function files which are .p so I cant see its contents. > > And each .p file calls few other .p files. > > I want to know w...

triangle wave function in C Code-S Functions
Dear All, I am trying to make a function to generate triangle wave in C code S-Functions. This will be used to make the carrier for PWM inverter simulation. does anyone have any idea about this, I've been searching but not result. Thanks anyone,, regards, Fred ...