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.

Similar Messages

  • Pass C++ Class Member Function as a callable function in AIR Native Extension

    I'm writing an ANE and I'd like to know if anyone has been able to pass a C++ class member function pointer as a callable function from AIR? I have tried this so far with a little bit of C++11 trickery and it's crashing. I've also statically linked the libstdc++ into my library, according to the documentation, in order to ensure that these features I use work correctly. I have code like so:
    FakeWorld* world = new FakeWorld();
    *numFunctions = 1;
    memberFunctions = (FRENamedFunction*) malloc(sizeof(FRENamedFunction) * (*numFunctions));
    ANEMemberFunction mCreateFakeBody = std::tr1::bind(&FakeWorld::createFakeBody, world, std::tr1::placeholders::_1, std::tr1::placeholders::_2, std::tr1::placeholders::_3, std::tr1::placeholders::_4);
    ANEFunction* createFakeBody = mCreateFakeBody.target<ANEFunction>();
    memberFunctions[0].name = (const uint8_t*) "createFakeBody";
    memberFunctions[0].functionData = NULL;
    memberFunctions[0].function = createFakeBody;
    FRESetContextNativeData(ctx, (void*)world);
    I just realized I'm using C here for allocating the member functions array.. silly me, but I don't think this is the cause of my issue. I refuse to believe that Adobe has built to the Native Extensions portion of the runtime in such a way that I have to cram every single function I want to create (natively) into a global, C formatted namespace (Especially since the documentation says that C is only required for the extenion and context initializing function interfacing and the rest of the code can be done in C++ or objective-C). So please let me know if and how this is possible and I thank you so much in advance for your time!P.
    P.S. Currently when I run this code, I can do the object initialization just fine. As soon as I invoke the "createFakeBody" method on the native side, the runtime dies and simply says:
    Problem signature:
      Problem Event Name: BEX
      Application Name: adl.exe
      Application Version: 3.1.0.4880
      Application Timestamp: 4eb7612e
      Fault Module Name: StackHash_0a9e
      Fault Module Version: 0.0.0.0
      Fault Module Timestamp: 00000000
      Exception Offset: 00000000
      Exception Code: c0000005
      Exception Data: 00000008
      OS Version: 6.1.7601.2.1.0.256.48
      Locale ID: 1033
      Additional Information 1: 0a9e
      Additional Information 2: 0a9e372d3b4ad19135b953a78882e789
      Additional Information 3: 0a9e
      Additional Information 4: 0a9e372d3b4ad19135b953a78882e789
    Read our privacy statement online:
      http://go.microsoft.com/fwlink/?linkid=104288&clcid=0x0409
    If the online privacy statement is not available, please read our privacy statement offline:
      C:\Windows\system32\en-US\erofflps.txt
    Thanks again for your assitance.

    It's been a little while since i've dealt with C++ and not up to speed on tr1 or C++0x, so forgive me if i'm not helping.
    The the examples of std::tr1::bind that i'm seeing out there seem to be either dereferencing the bound 'this' pointer when creating the bound method, i.e. in your case *world instead of world, or using std::tr1::ref(*world), therefore i believe that bind expects the bound parameters to be passed by reference.
    Given that the result of std::tr1::bind is callable (basing that on http://stackoverflow.com/questions/3678884/virtual-member-functions-and-stdtr1function-how -does-this-work) could you simplify to the following:
    memberFunctions[0].name = (const uint8_t*) "createFakeBody";
    memberFunctions[0].functionData = NULL;
    memberFunctions[0].function = std::tr1::bind(&FakeWorld::createFakeBody, *world, std::tr1::placeholders::_1, std::tr1::placeholders::_2, std::tr1::placeholders::_3, std::tr1::placeholders::_4);
    Or for an even simpler starting point, creating a test member function 'helloWorld' in FakeWorld that takes no arguments and using:
    memberFunctions[0].name = (const uint8_t*) "helloWorld";
    memberFunctions[0].functionData = NULL;
    memberFunctions[0].function = std::tr1::bind(&FakeWorld::helloWorld, *world);
    Hope this helps.

  • Reference to Class Member Functions

    Hello all.
    I have a question about references to LV class member functions. I have a small example to demonstrate my problem.
    My test class Base implements a reentrant public dynamic dispatch member function, doSomething.vi. 
    Another test class, Child, inherits Base and overrides the implementation of doSomething.vi.
    Now say I have an array of Base objects (which could include any objects from classes that inherit Base). I want to run the doSomething methods for all the objects in the array in parallel.
    In C++, I'd define a pointer to the virtual member function doSomething, and use it with each object in the array and the correct version of doSomething would be called.
    In Labview, the only way I've found to do it is like this:
    This is less than ideal, because it relies on every child class implementing doSomething, and relies on specific names for the inputs to the method. 
    Is there a better way to do this?
    Thank you,
    Zola

    I still suspect you are over-working this code and not leting LVOOP do tis thing.
    As I understand it you want to creae an active object but detemine its class at run time. The recent Architect summit touched on messaging for what they are calling a "worker Pool" pattern or what-not. YOu may want to search on the summit stuff. lacking that I'll share some images of where I did something similar ( I think). Note this is an older app and new stuff like the "Start Asyncronous call..." has been introduced making this even easier.
    I want to create a new Active Object (thread running in the background) so I invoke a method to do so
    It invokes the following that create some queues for talking to it and getting info back.
    Time does not permit me doing a complete write-up but I have assembled the above images into a LVOOP Albumn found here.
    When you click on one of those images you will get a large view as shown in this example.
    Just below that image you will find a link to the original thread where I posted the image and talked about it.
    I believe the best I can do for you at the moment is to urge you to browse my albumn and chase the links.
    That agllery was assembled in an attmept to help you and other before you asked. I hope it is helpful.
    Ben 
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • [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...

  • How to load function from derived class from dll

    Dear all,
    how to access extra function from derived class.
    for Example
    //==========================MyIShape.h
    class CMyIShape
    public:
    CMyIShape(){};
    virtual ~CMyIShape(){};
    virtual void Fn_DrawMe(){};
    // =========== this is ShapRectangle.dll
    //==========================ShapRectangle .h
    #include "MyIShape.h"
    class DLL_API ShapRectangle :public CMyIShape
    public:
    ShapRectangle(){};
    virtual ~ShapRectangle(){};
    virtual void Fn_DrawMe(){/*something here */};
    virtual void Fn_ChangeMe(){/*something here */};
    __declspec (dllexport) CMyIShape* CreateShape()
    // call the constructor of the actual implementation
    CMyIShape * m_Obj = new ShapRectangle();
    // return the created function
    return m_Obj;
    // =========== this is ShapCircle .dll
    //==========================ShapCircle .h
    #include "MyIShape.h"
    class DLL_API ShapCircle :public CMyIShape
    public:
    ShapCircle(){};
    virtual ~ShapCircle(){};
    virtual void Fn_DrawMe(){/*something here */};
    virtual void Fn_GetRadious(){/*something here */};
    __declspec (dllexport) CMyIShape* CreateShape()
    // call the constructor of the actual implementation
    CMyIShape * m_Obj = new ShapCircle();
    // return the created function
    return m_Obj;
    in exe there is no include header of of ShapCircle and ShapRectangle 
    and from the exe i use LoadLibrary and GetProcAddress .
    typedef CMyIShape* (*CREATE_OBJECT) ();
    CMyIShape*xCls ;
    //===================== from ShapeCircle.Dll
    pReg=  (CREATE_OBJECT)GetProcAddress (hInst ,"CreateShape");
    xCls = pReg();
    now xCls give all access of base class. but how to get pointer of funciton Fn_GetRadious() or how to get access.
    thanks in advance.

    could you please tell me in detail. why so. or any reference for it. i love to read.
    i don't know this is bad way.. but how? i would like to know.
    I indicated in the second sentence. Classes can be implemented differently by different compilers. For example, the alignment of member variables may differ. Also there is the pitfall that a class may be allocated within the DLL but deallocated in the client
    code. But the allocation/deallocation algorithms may differ across different compilers, and certainly between DEBUG and RELEASE mode. This means that you must ensure that if the DLL is compiled in Visual Studio 2010 / Debug mode, that the client code is also
    compiled in Visual Studio 2010 / Debug mode. Otherwise your program will be subject to mysterious crashes.
    is there any other way to archive same goal?
    Of course. DLL functionality should be exposed as a set of functions that accept and return POD data types. "POD" means "plain-ole-data" such as long, wchar_t*, bool, etc. Don't pass pointers to classes. 
    Obviously classes can be implemented within the DLL but they should be kept completely contained within the DLL. You might, for example, expose a function to allocate a class internally to the DLL and another function that can be called by the client code
    to free the class. And of course you can define other functions that can be used by the client code to indirectly call the class's methods.
    and why i need to give header file of ShapCircle and shapRectangle class, even i am not using in exe too. i though it is enough to give only MyIShape.h so with this any one can make new object.
    Indeed you don't have to, if you only want to call the public properties and methods that are defined within MyIShape.h.

  • 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/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

  • Calling a function in another class that is not the App delegate nor a sngl

    Hi all-
    OK- I have searched and read and searched, however I cannot figure out an easy way to call a function in another class if that class is not the app delegate (I have that down) nor a singleton (done that also- but too much code)
    If you use the method Rick posted:
    MainView *myMainView = [[MainView alloc] init];
    [MyMainView goTell];
    That works, however myMainView is a second instance of the class MainView- I want to talk to the instance/Class already instantiated.
    Is there a way to do that without making the class a singleton?
    Thanks!

    I had some trouble wrapping my head around this stuff at first too.
    I've gotten pretty good at letting my objects communicate with one another, however I don't think my method is the most efficient or organized way but I'll try to explain the basic idea.
    When you want a class to be able to talk to another class that's initialized elsewhere, the class your making should just have a pointer in it to the class you want to communicate with. Then at some point (during your init function for example) you should set the pointer to the class you're trying to message.
    for example in the app-delegate assume you have an instance of a MainView class
    and the app-delegate also makes an instance of a class called WorkClass
    If you want WorkClass to know about MainView just give it a pointer of MainView and set it when it's instantiated.
    So WorkClass might be defined something like this
    //WorkClass.h
    @import "MainView.h"
    @interface WorkClass : NSObject
    MainView *myPointerToTheMainView;
    @property (retain) myPointerToTheMainView;
    -(void)tellMainViewHello;
    @end
    //WorkClass.m
    @import "WorkClass.h"
    @implementation WorkClass
    @synthesize myPointerToTheMainView;//this makes getter and setter functions for
    //the pointer and allows us to use the dot
    //syntax to refrence it.
    -(void)tellMainViewHello
    [myPointerToTheMainView hello]; //sends a message to the main view
    //assume the class MainView has defined a
    //method -(void)hello
    @end
    now somewhere in the app delegate you would make the WorkClass instance and pass it a reference to the MainView class so that WorkClass would be able to call it's say hello method, and have the method go where you want (to the single instance of MainView owned by the app-delegate)
    ex:
    //somewhere in app-delegate's initialization
    //assume MainView *theMainView exists and is instantiated.
    WorkClass *myWorkClass = [[WorkClass alloc] init];
    myWorkClass.myPointerToTheMainView = theMainView; //now myWorkClass can speak with
    // the main view through it's
    // reference to it
    I hope that gets the basic idea across.
    I'm pretty new to Obj-c myself so if I made any mistakes or if anyone has a better way to go about this please feel free to add
    Message was edited by: kodafox

  • 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.

  • 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.

  • Dynamically start class member vi (non blocking)

    Hi folks,
    I've got a problem.
    I thought about building a framework, where i can dynamically start modules based on one class.
    The inherited classes representing the modules shold have a class member vi, that (containing a while loop) can be started dynamically.
    All selectes modules should be started from a loop starting one module after the other. Thus the dynamically start needs to be non blocking.
    I tried several ways, but allways reached the point, where the OOP approach limits the dynamically execution.
    Has anyone done something similar and can tell me how/if this is possible?
    Thanks in advance.
    Best regards,
    Balze

    Have a look at this link:
    http://lavag.org/topic/15035-lapdog-messaging-and-actor-framework/
    Or this:
    http://lavag.org/topic/14600-self-addressed-stamped-envelopes/
    On lavag.org there are a lot of discussion on that type of framework. There are a whole section for OOP, try to see if anything help you. 
    Look for Actor Framework or LapDog.
    Some talk alot on messages between loops, but that is to control free runing loops/vi's.
    Hope this helps.

  • Pointer to class object ?

    Is it possible to reference to a class object by an integer or string value ? I'm writing a scripting language, and for that I would like
    to be able to do something similair to this:
    Player p1 = new Player();
    int ref = (int) p1;
    Player p2 = (Player) ref;Where the outcome should be that p2.equals(p1).
    I've searched for this, but I got the feeling it is not possible. I did read something about hashCodes, is that something to look into ?
    Alternatively, I could give every Player an integer field called 'id', and then iterate through all Players to find the one with the given id, but I was
    wondering if there would be a more 'direct' approach.

    Great! A HashMap was exactly what I needed. I've now built it in, and it works like a charm.
    Encephalopathic wrote:What do you want to do with this information?The scripting language I'm writing is intended to be used by beginners in programming, for creating games.
    The language has objects, and for simplicity, I made all object fields and all variables in the language are doubles.
    After doing that, I'm not not sure if that was a good decision, but since it's allready implemented that way I don't want to change it anymore.
    In more advanced situations, people might want some object to refer to another object.
    For instance, if a group of a certain type is chasing a group of another type, and I the first group needs to split up. Then every individual from the first group needs a pointer to a member of the second group, so they each chase their own individual target.
    The language runs from a Java applet. I have an example game here:
    http://members.home.nl/bramdenhond/abcbasic/games/asteroids.html
    The explaination is in Dutch, but the idea of the game is to use the mouse to control the spaceship and shoot all asteroids without colliding with them.
    Thanks a lot for pointing me towards the HashMap! It was really helpful.
    For future reference, I'll place the code I used here:
        HashMap referencetable = new HashMap();
        int uniqueplayerid;
        //create
        Player p = new Player();
        referencetable.put(new Integer(uniqueplayerid), p);
        uniqueplayerid ++;
        //remove
        referencetable.remove(new Integer((int) indexedplayers[p].objvars[0]));
        //obtain
        int id = 12;
        TPlayer newp = (TPlayer) referencetable.get(new Integer(id));

  • Class/member variables usage in servlets and/or helper classes

    I just started on a new dev team and I saw in some of their code where the HttpSession is stored as a class/member variable of a servlet helper class, and I was not sure if this was ok to do or not? Will there be problems when multiple users are accessing the same code?
    To give some more detail, we are using WebLogic and using their Controller (.jpf) files as our servlet/action. Several helper files were created for the Controller file. In the Controller, the helper file (MyHelper.java) is instantiated, and then has a method invoked on it. One of the parameters to the method of the helper class is the HttpServletRequest object. In the method of the helper file, the very first line gets the session from the request object and assigns it to a class variable. Is this ok? If so, would it be better to pass in the instance of the HttpServletRequest object as a parameter to the constructor, which would set the class variable, or does it even matter? The class variable holding the session is used in several other methods, which are all invoked from the method that was invoked from the Controller.
    In the Controller file:
    MyHelper help = new MyHelper();
    help.doIt(request);MyHelper.java
    public class MyHelper {
        private HttpSession session;
        public void doIt(HttpServletRequest request) {
            session = request.getSession();
            String temp = test();
        private String test() {
            String s = session.getAttribute("test");
            return s; 
    }In the past when I have coded servlets, I just passed the request and/or session around to the other methods or classes that may have needed it. However, maybe I did not need to do that. I want to know if what is being done above will have any issues with the data getting "crossed" between users or anything of that sort.
    If anyone has any thoughts/comments/ideas about this I would greatly appreciate it.

    No thoughts from anyone?

  • Functions in a class

    Ok, I have found defining classes in .as files can be very
    useful for me. I have a few functions that are being called over
    and over again in different movies. There is what I want / need to
    do in order to stream line the creating and updating of the flash
    site. I want to see if I can put those same functions into a class
    (.as file) so I can access them from anywhere in the flash movie.
    The problem is when I just try to copy and paste the functions to
    the .as file (func.as) and then call the function by,
    func.FunctionName I get errors. The movie is calling the functions
    when buttons are pressed. Any ideas? I will attach some functions I
    am using that I would like to move to the func.as file.

    OK........ Couple of things I see....
    func.as
    package{
    public class func{ // This is the name of your class and as
    such, it needs a constructor.....
    public function func() {
    // Doesn't need to do anything
    Your import should be inside your package but outside the
    class definition
    You need to import your package into your Flash shell before
    you can call the BackToMenu funciton (this is the real reason for
    the error).
    If you get an error about not being able to nest packages,
    you'll need to adjust things
    package com.mysite.common {
    the above line will assume that you have folders relative to
    your flash shell of the same names.....
    com \ mysite \ common \ func.as
    If this doesn't make sense, just let me know. We'll get it
    straightened out.

  • Property not a class member... why?

    I'm looking at this sample code... metronome.h:
    ===== IMPORTANT =====
    This is sample code demonstrating API, technology or techniques in development.
    Although this sample code has been reviewed for technical accuracy, it is not
    final. Apple is supplying this information to help you plan for the adoption of
    the technologies and programming interfaces described herein. This information
    is subject to change, and software implemented based on this sample code should
    be tested with final operating system software and final documentation. Newer
    versions of this sample code may be provided with future seeds of the API or
    technology. For information about updates to this and other developer
    documentation, view the New & Updated sidebars in subsequent documentation
    seeds.
    =====================
    File: MetronomeView.h
    Abstract: MetronomeView builds and displays the primary user interface of the
    Metronome application.
    Version: 1.6
    Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc.
    ("Apple") in consideration of your agreement to the following terms, and your
    use, installation, modification or redistribution of this Apple software
    constitutes acceptance of these terms. If you do not agree with these terms,
    please do not use, install, modify or redistribute this Apple software.
    In consideration of your agreement to abide by the following terms, and subject
    to these terms, Apple grants you a personal, non-exclusive license, under
    Apple's copyrights in this original Apple software (the "Apple Software"), to
    use, reproduce, modify and redistribute the Apple Software, with or without
    modifications, in source and/or binary forms; provided that if you redistribute
    the Apple Software in its entirety and without modifications, you must retain
    this notice and the following text and disclaimers in all such redistributions
    of the Apple Software.
    Neither the name, trademarks, service marks or logos of Apple Inc. may be used
    to endorse or promote products derived from the Apple Software without specific
    prior written permission from Apple. Except as expressly stated in this notice,
    no other rights or licenses, express or implied, are granted by Apple herein,
    including but not limited to any patent rights that may be infringed by your
    derivative works or by other works in which the Apple Software may be
    incorporated.
    The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
    WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
    WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
    PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
    COMBINATION WITH YOUR PRODUCTS.
    IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
    CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
    GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR
    DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF
    CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
    APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    Copyright (C) 2008 Apple Inc. All Rights Reserved.
    #import <UIKit/UIKit.h>
    #import <QuartzCore/QuartzCore.h>
    #import "MetronomeViewController.h"
    #import "Constants.h"
    @class SoundEffect, MetronomeViewController;
    @interface MetronomeView : UIView {
    IBOutlet MetronomeViewController *metronomeViewController;
    UIImageView *metronomeArm;
    UIImageView *metronomeWeight;
    UILabel *tempoDisplay;
    NSThread *soundPlayerThread;
    SoundEffect *tickSound;
    SoundEffect *tockSound;
    CGFloat duration;
    NSUInteger beatNumber;
    BOOL armIsAnimating;
    BOOL tempoChangeInProgress;
    BOOL armIsAtRightExtreme;
    CGPoint lastLocation;
    // Property for beats per minute. Getting and setting this property alters the duration.
    // The accessors for this property are implemented, rather than synthesized by the compiler.
    @property NSUInteger bpm;
    @property (nonatomic, retain) NSThread *soundPlayerThread;
    @property (nonatomic, assign) MetronomeViewController *metronomeViewController;
    // Invoked when the user changes the time signature
    - (IBAction)updateAnimation:(id)sender;
    @end
    I'm looking at the property bpm. It isn't a class variable. I'm confused why this is... does it still work like the other class variables? I see that the the getter and setter methods are implemented rather than synthesized... But I still don't understand why it isn't a class member...
    Thanks.

    First, in Objective-C there is no "class member", only instance variable (and no class variable).
    Second, @property allows you to declare accessor methods without writing those :
    - (void)setName:(NSString *)aName;
    - (NSString *)name;
    That's just some line economizing.
    On the implementation side. @synthesize allows you to implement methods without writing those :
    - (void)setName:(NSString *)aName {
    if(name != aName)
    [name release];
    name = [aName retain];
    - (NSString *)name {
    return [[name retain] autorelease];
    Here it economize code again... Nothing more.
    @synthesize creates a default implementation for a specific property. However if you want to make specific modifications in your getter/setter you're forced to implement the methods yourself. In this case the reason is that there's no bpm ivar to link the properties to.
    But it could be another possibility, like, for example, when the user set the name, you want a nick-name ivar to be set as well. Here you need to use a specific method implementation and @synthesize can't help you.
    However, that are just implementation things... It doesn't change the behavior of the properties... And you can even use the dot-syntax on non-property methods if you want, it's just need to be KVC-compliant.

Maybe you are looking for

  • How do I sync my iPhone 4S with a new iTunes library without losing data?

    Hi, I have been using an iPhone 4S for a few months now. Yesterday my PC crashed and I had to reboot the whole system. So, obviously I had to reinstall iTunes. Now, when I am connecting my phone with iTunes, it is informing me that my phone was synce

  • Vista Business 64 on iMac - drivers wont install

    I installed Vista Business 64 bit on my 2.4 GHz iMac. The install went fine until I got to the initial boot of Vista. When I inserted the Mac disk to install the drivers, a little dialogue box popped up and said that Vista x64 was not supported on my

  • Reporting SP in Oracle 10g

    Hi Friends, Our Oracle version is 10.2.0.4.0. we have one cron job for reporting purpose. The stored proc with pull the 45 days back counts and populate counts into reporting tables. for some reasons this cron run successfully for 45 days and some ti

  • Create a SUS purchase order locally in SRM

    Hi guys we run a SRM 5.0 with SUS installed. I tried to create a PO locally as Purchaser with transaction type "SUPO SUS Purchase Order". It now says that "transaction type SUPO must not be used for object type BUS2201". Does my error belong to (1) I

  • I Cal Sync issue...The request for the account encountered an unexpected network error (error 60

    I have a Macbook Pro with OS 10.68 and cannot get my calendar to sync from Icloud.  All my other devices sync fine (Ipad, Iphone, Mac Tower...)  Any ideas on what is going wrong?  Thanks. Kimball Mitchell <Email Edited by Host>