Function pointer question

ok, let it be known that I am generally a c++ programmer, so some parts of c I am a bit unfamiliar with.  this generally includes generic (un-typesafe) casting and things of that nature (as c++ is supposed to be typesafe).
So here's my question.  I'm trying to strap a c interface on top of something.  The internal code allows for "generic" slots to be attached to a signal.... errm let me demonstrate with pseudo-code:
void func1(int);
bool func2(int,long,char*);
add_slot("signal1",func1);
add_slot("signal2",func2);
now... in the c++ portion, I can take advantage of templates in order to make it generic.  But when interfacing to C, I can't do that.  I was thinking I should just do something like:
typedef void* slot_func;
add_slot(char*,slot_func);
and just enforce the call at runtime.  it's what I have to do with the c++ portion, as due to the generic-ness (?) it can only be enforced at runtime...
can any c programmer point me in a better direction (if there is one)? I checked out some other code-bases, and things like irssi defines the "slot_func" as void f(void*,void*,void*,void*,void*); which just seems messy to me... *shrug*
thanks ina dvance for comments...

i3839 wrote:
If you only want to make a generic layer which provides a way to connect and combine multiple plugins, then it's much easier, I think. All it needs to do is let plugins find eachother and provide a communication channel.
Then it more or less boils down to two things, depending on the grand scheme: Plugins can generate events, and handle events.
yup, that's exactly what I was thinking...
i3839 wrote:All specific event details aren't important for the generic layer, that is something the plugins choose and implement. In this case each event is handled as a unique type: The plugin which handles it should know how to handle the data, if any. Think (void* data, int length), or just void* data, if you don't have variable length data but only strings and pointers to structures and stuff.
yeah, again dead-on to what I was thinking.  that would work, but I find it a bit sloppy... well... maybe it would *appear* cleaner doing:
typedef void* callback_data;
typedef bool (*callback)(callback_data);
i3839 wrote:The trickier part is what to do with multiple plugins handling the same event.
the internals would be c++ signals and slots (I may actually use a different implementation than boost or libsigc++) in which case, they are basically linked lists of slots assigned to a signal... the reason I defined the callback as a bool is because it's not hard to make a signal interruptable... and it's not hard to simply add a slot or add a slot at a certain position in the list (think priority!)... that way the following would happen:
signalX.emit(data);
//slot[0] called, returns true
//slot[1] called, returns true
//slot[2] called, returns false - emit ends
//slot[3] never called
i3839 wrote:Of course this way plugins may have too much freedom and the whole may be too dynamic, so you could restrict how plugins communicate with eachother.
yes, agreed... which is part of the reason I was straying from the raw "void*" stream of data...
I was trying to make it so specific parameters can be defined by each signal... and documented by each plugin itself:
pluginA defines a signal with the signature: void foo(int,void*), named "signalA"
pluginB tells the core to connect "void bar(int,void*)" to "signalA" (by name)
pluginC tells the core to connect "bool baz(struct stat)" to "signalA"
at runtime, the connection made by pluginB will succeed and work perfectly.  however, the connection made by pluginC will not work (it's undetectable at compile time... sigh), yet this is found as soon as signalA is emitted (called) - an error is reported and that slot is disconnected from the signal
this is, of course, all implemented in C++ and uses some RTTI (yeah yeah, I know... there's only space overhead for classes with virtual members.. which I don't use often)

Similar Messages

  • Assigning a variant string to a function pointer issue?

    Hello,
    This is a little complex for me to describe, so I will try my best to explain !
    I don't know if this is doable in C?
    Basically, I need a function pointer to hold the name of a function coming form a character array!
    From the examples I have seen, it seems that what I am trying to do is not the conventional way of doing function pointers, but I don't see any other way of doing what I need to do.
    In one instance, the function pointer in my code, will require to be assigned a function name like this:
    _g_BlkFuncs_ =_BUF_FUNC_PTR_ParseBlockStatus;
    and at other instances, the same function pointer needs to be assigned to a function called:
    _g_BlkFuncs_ =_INV_FUNC_PTR_ParseBlockStatus;
    and at other instances:
    _g_BlkFuncs_ =_AND_FUNC_PTR_ParseBlockStatus;
    or
    _g_BlkFuncs_ =_OR_FUNC_PTR_ParseBlockStatus;
    etc....
    The only time I will know which function to assign is when I will retrieve the first part of the function name from a table called
    _x_UserPrgBlock_. The first part being the name differentiator such as "_BUF_", "_INV_", "_AND_", "_OR_" and so forth which
    is initially stored in the one of the table members called m_LogicElement_ residing in the _x_UserPrgBlock_ table or struct.
    In the example below, I made it simple by hard coding the assigning of the m_LogicElement_ member as "_BUF_" (see the line commented as "Manual assignment line" below). In reality the  m_LogicElement_ member is assigned from
    a user defined string which will vary from time to time. 
    Here is the sample snippet which shows the issue.
    ================================STRUCT.h
    #ifndef STRUCT_H
    #define STRUCT_H
    typedef struct USR_PRG_CNV{ // User program converter table
    char m_LogicElement_[2][knst_BUF_LOGIC_ELEM]; // Name of the logic block
    } User_Prg_Block;
    #endif
    =================================_BUF.h
    #ifndef BUF_H
    #define BUF_H
    void _BUF_FUNC_PTR_ParseBlockStatus(void);
    #endif
    ================================_BUF.c
    void _BUF_FUNC_PTR_ParseBlockStatus(void){
    int i = 0;
    i = 10;
    ===============================UPC.h
    #ifndef UPC_H
    #define UPC_H
    void AssignmentFunc();
    #endif
    ===============================UPC.c
    User_Prg_Block _x_UserPrgBlock_[2];
    void AssignmentFunc(){
    strcpy(_x_UserPrgBlock_[0].m_LogicElement_, "_BUF_"); // Manual assignment line
    ===============================DFP.c
    #include "_BUF.h"
    void (*_g_BlkFuncs_) (void);
    char volatile _g_FuncPtrStrVariant_[35];
    void SomeFunction(){
    strcpy(_g_FuncPtrStrVariant_, _x_UserPrgBlock_[0].m_LogicElement_); // Get "_BUF_"
    strcat(_g_FuncPtrStrVariant_, "FUNC_PTR_ParseBlockStatus"); // Complete the function name
    // Now try to assign the full function name to the function pointer
    //_g_BlkFuncs_ = _BUF_FUNC_PTR_ParseBlockStatus;
    //_g_BlkFuncs_ = &_g_FuncPtrStrVariant_;
    _g_BlkFuncs_ = _g_FuncPtrStrVariant_; // ???
    ==============================Main.c
    void main(){
    AssignmentFunc();
    SomeFunction();
    In reference to the following line listed above:
    _g_BlkFuncs_ = _g_FuncPtrStrVariant_;
    I do realize that conventionally, it should be:
    _g_BlkFuncs_ =_BUF_FUNC_PTR_ParseBlockStatus;
    The problem I find myself faced with is that the function that "_g_BlkFuncs_" points to, has to vary in accordance to the name of the function stored in the _g_FuncPtrStrVariant_ character array! The reason is that the _g_FuncPtrStrVariant_
    array is actually built up to the name of the function based on the current contents of m_LogicElement_ residing in the _x_UserPrgBlock_ table.
    I think!!!!! that even if I use an array of function pointers, it won't solve the issue.
    In summary, in C, is there a way to assign a name of a function built from a character array to a function pointer?
    All help sincerely appreciated!
    Thanks

    I am interpreting your question a little different than Brian.
    If I understand you correctly you are asking:  "Given the name of a function as a string, how do I get a pointer to that function".
    The unfortunately fact is that C++ does not support reflection, so getting a function by name is not possible.  By the time the linker has done its thing, the function name has been stripped from code.
    This means if you need to support string lookup of a function name you need to support an alternate mechanism to handle this.  If you were using C++, a map would be an ideal mechanism.  C can still do this, but the mechanism is a lot uglier
    due to the lack of data structures like std::string and std::map.

  • Function Pointer Problem?

    I need to call a function that is in main of a running class from another class. How could I do that?
    I have a single GUI frame that use for display all info sent (via TCP/IP) from the object which called by several short java programs (all running at the same time). I want to call a function that reside in those short java programs to terminate a specific program immediately as soon as the user click cancel button on the GUI.
    I talked with C/C++ programmer, which know nothing about JAVA, and he said that I will probably need to do function pointers but , from what I know, there is no function pointer in Java.
    Please advice! It would be very helpful if you could provide some short example code since I am just a beginner. Thanks.

    I need to call a function that is in main of a
    running class from another class. How could I do
    that?
    I have a single GUI frame that use for display all
    info sent (via TCP/IP) from the object which called
    by several short java programs (all running at the
    same time). I want to call a function that reside in
    those short java programs to terminate a specific
    program immediately as soon as the user click cancel
    button on the GUI.
    I talked with C/C++ programmer, which know nothing
    about JAVA, and he said that I will probably need to
    do function pointers but , from what I know, there is
    no function pointer in Java.
    Please advice! It would be very helpful if you could
    provide some short example code since I am just a
    beginner. Thanks.The closest thing to a function pointer in Java is an Interface.
    inteface FunctionPointer // don't call your interface this
        void go();
    }Then you can pass it to another thread:
    FunctionPointer fp = new FunctionPointer() {
        public void go()
            // code here
    myGuiClass.executeAsap(fp);However, I don't think this, or a function pointer solves your problem. There is no reliable way to arbitrarily stop a thread.
    What you can do is something like this:
    class StoppableRunnable
        private volatile boolean continue = true;
        public void kill()
            continue = false;
        public void run()
            while (continue) {
                //do stuff
                if (!continue) break; // maybe you want this too
                // do more stuff
    }Let me know if this answers your question.

  • [SOLVED] Passing a non-static member function as a function pointer

    I need to pass a function pointer to a public method to a system call, nftw() to be precise.
    I know that member functions don't match the required signature because of the hidden 'this' pointer, but
    the only way to work around that is by using a small wrapper function that makes use of a global variable (the object of which I want to call the method).
    Speaking in code, this is the way I've solved the problem currently:
    // create a global variable here
    static MyObject obj;
    static int myObject_method_wrapper(const char *fpath, const struct stat *sb, int tflag, struct FTW *ftwbuf) {
    return obj.handleDirEntry(fpath, sb, tflag, ftwbuf);
    // somewhere in main()
    nftw(walkroot, myObject_method_wrapper, 20, FTW_PHYS);
    Now, my question: Can't this be done without a global instance of MyObject? It is pointed out here that other ways are existent, but sadly they are not mentioned.
    Glad if someone could help me out!
    Last edited by n0stradamus (2012-04-24 22:59:47)

    I think you are stuck:
    1. You are not in control of the interface (of nftw), and furthermore,
    2. You are not in control of any of the parameters sent to the callback.
    nftw has no idea which one of your objects it is supposed to reference, and
    there's no apparent way to tell it.
    But given this situation, are you sure it makes sense to use a non-static
    member?  It seems kind of strange to me-- any instance-specific data is
    necessarily going to be independent of the function calls!  So even if you
    engineer something to avoid using a global, whatever you engineer is still
    going to involve some *arbitrary* instance of your class (e.g. peterb's
    solution, which uses the most recently created instance).  The arbitrary-ness
    doesn't feel right, since it sort of implicitly says that none of the instance
    data is important.  No important instance-specific data sounds like static...

  • Is it possible to get a function pointer to a getter/setter function

    Please do not respond with questions asking why, what usage, or suggesting alternative ideas.
    Looking for a yes/no answer, from someone who actually knows.
    The generally used workaround for this, is to use a regular function instead of a getter/setter.  This results in having to have ( ) after the function variable obviously.  The question is, can a Function variable be assigned to a getter/setter function and retain its attribute of not needing brackets.  Everything I have read seems to imply it is not, but I am looking for a definitive answer.
    Below is some Pseudo code representing the question:
    public class Foo(){
         private var prop:Object;
         public function get Prop():Object{return prop;}
         public function set Prop(o:Object):void{prop=o;}
    //==================
    var GlobalFuncVar:Function = Foo.<get Prop>;
    *** - If Foo.Prop is used, it returns the value. how can the function pointer be accessed...

    The answer Should be no, but with a dynamic Object you can make this posible where a property call is actually a shortcut to a function.
    But this is a terrible practice because you will confuse anyone looking at the code when they feel its a property its actually a method being used.
    NOT AN ALTERNATIVE SOLUTION, SAME SOLUTION WITH GOOD ENCAPSULATION, DELEGATE to an object.
    use a get and set to set an object that has a common method to execute such as execute()
    then call your prop functionCall or whatever you choose.  myObject.functionCall= (ICanExecute type)
    now that its in myObject.functionCall.ecex()
    swap out your behavior that is required, but keep it clear to the user of your code.

  • CRM FUNCTIONAL interview questions and answers

    Dear Friends,
    Good Afternoon..!!!
    can you tell me the CRM FUNCTIONAL interview questions with answers if avialable.....
    Regards,
    Dhananjaya

    Dear friends,
    Can any body forward me interview questions and answers
    can any body tell me where can i get crm functional video tuter

  • Travel Management functions interview question and answers

    Hi Guys,
    I wanted to know Travel Management functions interview question and answers , it is most urgent for me.
    Your detail response will be highly appreciated.
    Thanks – Sam.

    Check this site
    http://help.sap.com/saphelp_470/helpdata/en/73/6bf037f1d6b302e10000009b38f889/frameset.htm
    Regards,
    Ruben

  • Oracle Asset (Functional) Practice Questions for Interviews and Exam

    https://www.createspace.com/3495382
    http://www.amazon.com/Functional-Questions-Interviews-Certification-Examination/dp/1456311581/ref=sr_1_4?ie=UTF8&s=books&qid=1289178586&sr=8-4
    List Price: $29.99
    Add to Cart
    Oracle Asset (Functional) Practice Questions for Interviews and Certification Examination (Release 11i and 12)
    Functional Consultant
    Authored by Erp Gold
    This book contains 150 Oracle Asset Practice Questions for functional consultants. Very useful for interviews and certification examinations.
    Publication Date:
    Oct 26 2010
    ISBN/EAN13:
    1456311581 / 9781456311582
    Page Count:
    94
    Binding Type:
    US Trade Paper
    Trim Size:
    6" x 9"
    Language:
    English
    Color:
    Black and White
    Related Categories:
    Computers / General

    Reported as spam!

  • Oracle Asset (Functional) Practice Questions for Interviews and Certificati

    https://www.createspace.com/3495382
    List Price: $29.99
    Add to Cart
    Oracle Asset (Functional) Practice Questions for Interviews and Certification Examination (Release 11i and 12)
    Functional Consultant
    Authored by Erp Gold
    This book contains 150 Oracle Asset Practice Questions for functional consultants. Very useful for interviews and certification examinations.
    Publication Date:
    Oct 26 2010
    ISBN/EAN13:
    1456311581 / 9781456311582
    Page Count:
    94
    Binding Type:
    US Trade Paper
    Trim Size:
    6" x 9"
    Language:
    English
    Color:
    Black and White
    Related Categories:
    Computers / General

    Reported as spam!

  • Function Pointer/Parent functionality in Java?

    Hi,
    I'm fairly new to Java and still finding my way around.
    I have to write a game for a university project and need some functionality simalar to that of function pointers in C++. Basically, the game has several different types of objects (ships, planets, projectiles, etc). I have a class which runs a physics simulation, if I want an object to be included in the physics simulation, I instanciate a physics object class within that object and add a reference of the physics object to the physics simulator.
    When the physics simulator detects a collision between two physics objects, i want the appropriate methods to be called within the two objects containing the physics objects. If i was using C++, i would simply construct each physics object with a function pointer to the method i want to run in the event of a collision.
    I hope that made some sense...
    Thankyou in advance for any input =)

    If i was using C++But are you familiar with object-oriented programming? And Patterns?
    Check out the Strategy Pattern: http://en.wikipedia.org/wiki/Strategy_pattern

  • Binding function pointer to class member fnction

    Hi,
    I have created a function pointer to class nonstatic member function. But facing some compilation issue. Can someone help on this.
    #include "stdafx.h"
    #include "iostream"
    #include <functional>
    using namespace std;
    using namespace std::placeholders;
    class A
    public:
    void Fun(void* param, bool b){cout<<"Hi\n";}
    typedef void (A::*fptr)(void*,bool);
    int _tmain(int argc, _TCHAR* argv[])
    fptr obj;
    auto f = std::bind(&A::Fun, &obj,_1,_2);
    f(NULL,1);
    return 0;

    See some samples about std::bind and std::function
    http://en.cppreference.com/w/cpp/utility/functional/bind
    http://en.cppreference.com/w/cpp/utility/functional/function
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Vi reference = function pointer for external DLL?

    So I'm porting this simple program from C to LabVIEW. All it does is getting some signals from an haptics hardware (Sensable Phantom Omni). It should be simple, but it has shown several complications. (been stuck for 2 weeks )
    I successfully imported the hardware's DLL with all of its functions (using LV 8.2, because 8.5 and 8.6 's wizard sucks).
    But there is a function whose argument is a function pointer:
    hUpdateHandle = hdScheduleAsynchronous(updateDeviceCallback, 0, HD_MAX_SCHEDULER_PRIORITY);
     I already have the corresponding VI for updateDeviceCallback (which gets a (void *) that does not really use, and returns an int).
    hdScheduleAsynchronous is part of the hardware's API (I can't mess with it, nor I know what's inside), and as first argument expects a function pointer.
    Can I use the Open VI reference node to get the 'pointer' for my VI and then feed it as an argument for the external DLL? How do I properly cast the VI ref datatype into a function pointer?
    Solved!
    Go to Solution.
    Attachments:
    QueryDevice.c ‏9 KB
    updateDeviceCallback.vi ‏14 KB

    JavierRuiz wrote:
    So I'm porting this simple program from C to LabVIEW. All it does is getting some signals from an haptics hardware (Sensable Phantom Omni). It should be simple, but it has shown several complications. (been stuck for 2 weeks )
    I successfully imported the hardware's DLL with all of its functions (using LV 8.2, because 8.5 and 8.6 's wizard sucks).
    But there is a function whose argument is a function pointer:
    hUpdateHandle = hdScheduleAsynchronous(updateDeviceCallback, 0, HD_MAX_SCHEDULER_PRIORITY);
     I already have the corresponding VI for updateDeviceCallback (which gets a (void *) that does not really use, and returns an int).
    hdScheduleAsynchronous is part of the hardware's API (I can't mess with it, nor I know what's inside), and as first argument expects a function pointer.
    Can I use the Open VI reference node to get the 'pointer' for my VI and then feed it as an argument for the external DLL? How do I properly cast the VI ref datatype into a function pointer?
    LabVIEW has no concept that can translate seemlessly to function pointers and there is certainly no sensible way to make the Call Library Node support something like this.
    There are possibilities to create a DLL from your callback VI and import the function using Windows API calls to pass it as a function pointer to your other function. But this is involved and quite dirty and most importantenly a total nightmare to maintain, since things go completely awry if your DLL is created in a different LabVIEW version than the LabVIEW version you call it with. This may seem like a piece of cake now but whoever will have to upgrade your software to a new LabVIEW version later will love you to the point that they will feel like sending you as the original programmer a nice little present that blows in your face when opened 
    The only feasable way is to write a wrapper DLL in C that translates between something more LabVIEW friendly like a user event and the actual callback function mechanisme.
    Rolf Kalbermatter
    Message Edited by rolfk on 06-09-2009 10:24 AM
    Rolf Kalbermatter
    CIT Engineering Netherlands
    a division of Test & Measurement Solutions

  • Floating point question

    I am trying to create a price attribute, so I need to places after the decimal point. I how do I set that when I create a table?

    Example from Help section in Oracle SQL Developer:
    Connected to:
    Oracle Database 11g Enterprise Edition Release 11.1.0.6.0 - Production
    With the OLAP and Data Mining options
    SQL> set serverout on
    SQL> DECLARE  -- Declare variables here.
      2    monthly_salary         NUMBER(6);  -- This is the monthly salary.
      3    number_of_days_worked  NUMBER(2);  -- This is the days in one month.
      4    pay_per_day            NUMBER(6,2); -- Calculate this value.
      5  BEGIN
      6  -- First assign values to the variables.
      7    monthly_salary := 2290;
      8    number_of_days_worked := 21;
      9
    10  -- Now calculate the value on the following line.
    11    pay_per_day := monthly_salary/number_of_days_worked;
    12
    13  -- the following displays output from the PL/SQL block
    14    DBMS_OUTPUT.PUT_LINE('The pay per day is ' || TO_CHAR(pay_per_day));
    15
    16  EXCEPTION
    17  /* This is a simple example of an exeception handler to trap division by zero.
    18     In actual practice, it would be best to check whether a variable is
    19     zero before using it as a divisor. */
    20    WHEN ZERO_DIVIDE THEN
    21        pay_per_day := 0; -- set to 0 if divisor equals 0
    22  END;
    23  /
    The pay per day is 109.05
    PL/SQL procedure successfully completed.
    SQL>It's not create table statement which you need but one can see in this example answer on your " Floating point question".
    HTH
    Message was edited by:
    Faust

  • Function Point Analysis in SAP

    Dear All,
    I am a Technical Consultant, currently working with the Quality Team on a temporary basis.
    Can anyone please point out how to perform estimation of projects in SAP with the help of Function Point (FP).
    If it is difficult with FP then give some alternate methods.
    Regards,
    Arun Krishnan.G

    Dear,
    As found in other reply as: Function Point Analysis is independent of technology, methodology or platform, so there is no function point analysis specific for sap, rather you should familiarize with the fundamentals of FPA.
    And as you might know, FAP is used to determine whether a given a tool, an environment or a language is more productive when compared to others.
    There are lot of links you can found related to FPA and IFPUG. Check with net search.
    Regards,
    Syed Hussain.

  • Function Point Analysis for SAP BW Projects

    Hello All,
    Have been assigned a task to come up with Function Point
    analysis for SAP BW projects.
    Any help will be appreciated.
    Thanks,
    Mainak

    Hi Mainak,
      Function Point Analysis is independent of technology, methodology or platform, so there is no function point analysis specific for sap bw, rather you should familiarize with the fundamentals of FPA.
      And as you might know, FAP is used to determine whether a given a tool, an environment or a language is more productive when compared to others.
      I can send you good links if you can give me your email-id.
    Hope this helps...
    Thanks,
    Raj

Maybe you are looking for

  • 4GB DDR 3 Modules On MSI X48C Platinum

    Hi, so with the 7.4 bios it reads the sizes right, now i have 2 x 4gb kingmax 1333 ram but, it doesnt post with them is it compatibility or can it be the ram is faulty?

  • Cannot either install or uninstall iTunes

    I tried to update iTunes with v12.1.2 on my Win 8 64-bit computer by running the installation file over the current v12.0 and the installation failed. This is what occurred: 1. The initial error I received was that it did not have access to the "C:\P

  • Floating keyboard problem

    I have this floating keyboard problem. Is there a fix to this? I jail broke my device and I know it's not anything I downloaded after that because none of the things I downloaded have anything to do with mail or photos. This only happens when I try t

  • Divs to stick together?

    I have a page i'm working on at http://www.metrocog.org/index061613.html I'm trying to learn how to postion the div on the right of the slideshow so it dose not move when the page is resized. Right now I have them together but if you shrink the page

  • Permanently delete iCloud files

    How do I permanently delete all iCloud files?