Help with design issue - c++

Here is my problem.
I'm using a physics library called Box2D. I'm able to hook up a listener that will tell me when 2 fixtures collide.
Essentially the way Box2D works is by creating b2Bodies. Therefore, I only know which b2Body the fixture that collided belongs to. In my game, I have an Entity, and from that I have a PhisicsEntity. A PhysicsEntity holds a pointer to a b2Body. It also has a sendMessage method that comes from Entity. The problem is, from the b2Body, how do I send the PhysicsEntity a collision message. What I thought of doing was to set the userData void* of the b2Body to its corresponding PhysicsEntity. It seems very wrong to have to cast a void* to do this though.
Is there a better way that I could very quickly know the Physics Entity associated with the b2Body without casting or lookup?
Thanks

This is exactly the purpose that fields like that userData field are for — to refer to your application's data related to the library's object. This is an entirely appropriate use of void *.
If you were asking about C, I would say that you should also not have to use any casts, as converting to and from void * can be done without any casts and needing to use a cast is a sign of a possible problem, but if I recall correctly C++ requires those casts (I do not use C++ enough to be sure).

That's actually exactly what the userData pointer is meant for. It's a fairly standard paradigm - look at functions such as pthread_create or CreateThread for another example.
If you encounter a library that doesn't allow you to use a void * (or not safely - such as storing it locally as an int) then you can use an std::map to resolve the type. That's slower and with much more overhead though.

Related

Splitted interface of library (ChessGame with Figures etc) vs user's law to delete every pointer

Sometimes it's convenient to split interface of some system/library in more than one class.
For example, consider idea of library for playing Chess. Its interface would use (and deliver to players) different object for every single game and - during game - another object for every figure.
In Java there wouldn't be such a problem. But in C++, a library user can delete (or make attempt to delete) every pointer he'll get. Even shared_ptr/weak_ptr.
What do you think about such situations? Should I use in my interface wrapping classes that deleting isn't dangerous?
What is an usual way for such dilemmas?
Is there a way that STL smart pointers would help? I heard that they should be used always and only to express ownership, so they seem to have nothing to do with this issue (Chess is owner of SingleGame, SingleGame is owner of every Figure).
PS did I use correct tags/subject?
You can't stop a user from breaking stuff. As others have suggested, use smart pointers. With C++11, there is no reason not to use them in new code. If the user still breaks it, that's their fault. You can't design a library that is completely foolproof. You can just do your best to disuade foolish behavior.
As others have said, smart pointers (or other RAII schemes) are often a great idea. They can clearly indicate ownership and at the same time provide an automatic mechanism for managing it. Try using such if you can.
But really, no reasonable C++ programmer should be blindly calling delete on every pointer they get. When they use a library/API/whatever which returns a pointer/handle/resource/etc they should be reading its documentation to tell them whether or not they will be responsible for deallocation and if so then when technique should be used.
So at a minimum, just make sure your public interface clearly indicates when ownership is passed to the caller and what method they should use for cleanup.

Decide if it is a process or thread in C++

Give a void * variable as input (can only point to a process or thread), I'd like to first determine its type and then convert it to that type.
How should I do that in C++? I know it's a dumb question, but I've never done C/C++ before and can't think C/C++ way yet.
EDIT: I need to achieve this on both Linux and Windows.
You can't. Pointers carry two pieces of information: the location in memory to where they point and the type of the pointed object. With a void * this last information is omitted, and there's no way to reconstruct what type it pointed to. So, you need to carry along this pointer another value that specifies what it actually points to (you can use e.g. an enum).
The only facility somehow related to this task in C++ is RTTI, but it works only on pointers to polymorphic classes (RTTI usually exploits the vtable of the object to store additional information about the dynamic type of the pointer, but the vtable can be accessed and correctly interpreted only if it is known that the object belongs to a particular polymorphic class hierarchy).
I'm looking for a uniform way to pass pid or tid in but will treat the ids differently. Sorry, I might not properly state my problem.
Well, this is a completely different thing... if you need to pass around your PID/TID inside a void * you could simply create a struct or something like that with a member for the ID and one to store if such ID is a PID or a TID.
There are a bunch of solutions.
For example, keep track of all the Process and Thread objects created. Store these each in a set<void*>, and check for the presence of that void* in the ProcessSet or ThreadSet. This solution just requires that you know where the objects are allocated.
Other approaches require some ability to deference.
Most obviously, if you have defined the types Process and Thread, give them a common base class and pass that around instead of a void*. This is basic OOP. You can then use RTTI to find the derived type. But most likely in this situation, a refactor/ redesign would obviate the need for this in the first place.
If you cannot add a base type, you could add a wrapper, and pass that around. This works even if all you ever see is a void*. This is similar to the set<> solution in that you require to know the type when it is allocated.
struct ProcessOrThread
{
bool isProcess_;
void* handle_;
};
All this really boils down to: If you know the type to start with, avoid throwing that information away in the first place.
What system are you talking about? On Linux, I would say your question does not make any sense, because processes don't have addresses (a pid_t as returned by fork or getpid is an integer).
You could use libraries which wrap processes and threads as objects, like Qt does (and it works on Linux, Windows, MaCOSX...). (and they you could e.g. use dynamic_cast or Qt meta object system, if you are sure the pointer points to either an instance of QThread or an instance of QProcess).
The only thing you can do is attach a type information to the process/thread structures.

What is a good way to share an object between classes?

What is a good way to share an instance of an object between several classes in a class hierarchy? I have the following situation:
class texture_manager;
class world {
...
std::vector<object> objects_;
skybox skybox_;
}
I currently implemented texture_manager as a singleton, and clients call its instancing method from anywhere in the code. texture_manager needs to be used by objects in the objects_ vector, by skybox_, and possibly by other classes as well that may or may not be part of the world class.
As I am trying to limit the use of singletons in my code, do you recommend any alternatives to this approach? One solution that came to mind would be to pass a texture_manager reference as an argument to the constructors of all classes that need access to it. Thanks.
The general answer to that question is to use ::std::shared_ptr. Or if you don't have that, ::std::tr1::shared_ptr, or if you don't have that, ::boost::shared_ptr.
In your particular case, I would recommend one of a few different approaches:
One possibility is, of course, the shared_ptr approach. You basically pass around your pointer to everybody who needs the object, and it's automatically destroyed when none of them need it anymore. Though if your texture manager is going to end up with pointers to the objects pointing at it, you're creating a reference cycle, and that will have to be handled very carefully.
Another possibility is just to declare it as a local variable in main and pass it as a pointer or reference to everybody who needs it. It won't be going away until your program is finished that way, and you shouldn't have to worry about managing the lifetime. A bare pointer or reference is just fine in this case.
A third possibility is one of the sort of vaguely acceptable uses of something sort of like a singleton. And this deserves a detailed explanation.
You make a singleton who's only job is to hand out useful pointers to things. A key feature it has is the ability to tell it what thing to hand out a pointer to. It's kind of like a global configurable factory.
This allows you to escape from the huge testing issues you create with a singleton in general. Just tell it to hand out a pointer to a stub object when it comes time to test things.
It also allows you to escape from the access control/security issue (yes, they create security issues as well) that a singleton represents for the same reason. You can temporarily tell it to pass out a pointer to an object that doesn't allow access to things that the section of code you're about to execute doesn't need access to. This idea is generally referred to as the principle of least authority.
The main reason to use this is that it saves you the problem of figuring out who needs your pointer and handing it to them. This is also the main reason not to use it, thinking that through is good for you. You also introduce the possibility that two things that expected to get the same pointer to a texture manager actually get pointers to a different texture manager because of a control flow you didn't anticipate, which is basically the result of the sloppy thinking that caused you to use the Singleton in the first place. Lastly, Singletons are so awful, that even this more benign use of them makes me itchy.
Personally, in your case, I would recommend approach #2, just creating it on the stack in main and passing in a pointer to wherever it's needed. It will make you think more carefully about the structure of your program, and this sort of object should probably live for your entire program's lifetime anyway.

Is a dynamic cast appropriate here?

Say in a game, we have Entities that communicate with each other. Say a player collides with an Item and now, that item should be placed in his std::vector<Item*>
When the player receives the collision message, he receives the item as an Entity*. Would it then be appropriate for the player to cast it as an item, and if the cast succeeds, to push the item into the inventory?
Even if the game sent him a HIT_ITEM message, he would still need to cast it to push it in.
Thanks
dynamic_cast helps you check the validity while performing downcasting.
It returns a NULL or throws an exception(std::bad_cast for References)if the pointer or the reference cannot be safely downcasted.
It is unclear to say unless you show us the class structures.
If you can satisfactorily answer these questions for yourself, then yes.
Why does the player receive the collision message with an Entity* rather than an Item*?
at the point of the potential cast, are you SURE it'll be of dynamic type item? What if it isn't ?
Is there any way you could relatively painlessly redesign your code to avoid the cast?
Anyway, don't be dogmatic. If in the current circumstances a downcast is more convenient than other things, do it. IMHO
The main question you should ask yourself is- could I just make this a virtual function on Entity? In this case, I would probably say "no", because it doesn't make sense for non-Items to know or care about what you're gonna do with an Item. So dynamic_cast probably is the right solution- you can safely handle the case of null coming back and it keeps the other derived classes from having to know anything about Item.
How about adding a type member together with a GetType() function to the base class? This is how I usually solve those "casting" problems.
In addition don't forget to turn on RTTI if you are going to use dynamic_cast (please ignore it this was obvious).

JNI vs. C++ Object Instances

I have just started at a new job. Here we are new to using JNI ( for bridging C++ / Java ). I am new to JNI so please forgive my noobness :)
In our (win32) Java app we are loading a C++ DLL. On the Java side we have several instances of "SomeJClass" each of these instances needs access to corresponding instance of "SomeCClass" on the DLL side.
The DLL exposes entry-points such as GlobalDoSomethingInC(). Here I must call the instance method of Doer::DoSomethingInC(). So I need a smooth way to map the respective this-pointers.
I also need to do the same mapping when a DLL thread discovers something interesting that it needs to notify the corresponding Java-instance of.
I can think of several solutions, but I do not like them too much. My question is, is there a better way than this ?
1 Java calls C:GetNewInstance(). This returns an int that is actually a pointer to the new C instance. Java stores it in m_myCInstance. Then Java calls GlobalDoSomethingInC(), and
1a
// DLL global
void GlobalDoSomethingInC()
{
// retrive this pointer
//calling back to Java:
jobj tmpJ = NewGlobalRef( env, obj );
Doer* myDoer = <reinterpret_cast>( Doer )tmpJ->GetMyCInstance();
myDoer->DoSomething();
DeleteGlobalRef( env, tmpJ );
// Arrrrgh
}
1b or:
// for **every call** that Java adds a parameter,
//which is the stored int:m_myCInstance, and
Doer* myDoer = <reinterpret_cast>( Doer )instanceParam->DoSomethingInC();
// Can we do better that this?
2 For calling from C to Java, things look, maybe, better
In the constructor C calls back into Java and stores
the Java instance reference
in a member variable. m_myJInstance.
In all subsequent calls m_myJInstance can be used to call back Java.
In the destructor we need to call DeleteGlobalRef( env, m_myJInstance );
Not too bad I suppose. But it really safe to store the jobject reference.
I mean: What happens when the GC moves the object around?
3 Our present solution does "work". But it belongs on rather on http://www.codinghorror.com/blog/ :)
Thanx
Typically this will depend on your environment somewhat. I've only used KNI, which is even more primitive than JNI. I think a fair bit of ugliness is unavoidable, as you're mixing memory tracking across two systems, only one of which has GC.
In general, I found it best to wrap all of the calls out the C code in functions that took care of the nasty casting, which I think is unavoidable. (BTW, I'll use C to mean non-Java code here)
On the C side, movement of Java objects is definitely a potential problem. It will depend on your platform, but I would expect that as long as you are within the lib, you can expect no Java GC to occur, so your objects are stable. YOU NEED TO BE SURE OF THIS. On the other hand, if it's not the case, you're pretty much screwed. Assuming it is the case, you want to do the same thing of isolating dereferencing/casting to the function that's exposed to JNI, so that you can happily work with normal C objects in all of your called functions.
Where it can get really ugly is if you can have objects go out of scope on either side, as then potentially either side can be holding a reference to your object. Here we used finalizers on the Java side, as well as destructors on the C side. It wasn't pretty, but I think that what somewhat unavoidable.
So, short answer, it will be somewhat ugly, isolate the ugliness around the interface between the two languages, so that for the bulk of the work, in either language, you don't have to worry about such things.
It's also worth having a base class for objects that exist over this interface, as here you can also isolate some ugliness.
jobject is an opaque handle to an object. May vary in runtime implementation (see Android 2.x vs 4.x), but just trust that it is an opaque object.
The current solution is probably correct. If you must stash a jobject in native code, you must convert it to a Global reference -- If you call NewGlobalRef, the object's refcount has increased, and will not be disposed until you call DeleteGlobalRef (and the GC has noticed it is unreachable otherwise)