I've got a piece of code in which I use boost::unsafe_any_cast<void*>(&boost::any anyInstance) to obtain the content pointer of a boost::any object.
The code is this below:
boost::any staticResult; //contains a private pointer called content
f(staticResult); //makes the content pointer a null pointer
void* voidStaticResult = boost::unsafe_any_cast<void*>(&staticResult);
Unfortunately, debugging, I see that the content pointer in staticResult is NULL (0x00000000) while voidStaticResult is 0x00000004.
(Apparently there's no reason for that. Have you got any ideas?)
EDIT: The function f() calls a dll creating an instance of an object. The instance is pointed by the content pointer of staticResult. I need to pass the pointer to another function, but it seems to me there's no easy way to "cast" boost::any to a pointer to the instantiated class. Any other solution would be great.
Probably unsafe any cast is only valid for non empty any's. It is unsafe and unchecked.
Any is often implemented as a pointer at a block of memory where there is a vtable followed by the object instance. So to get a pointer to the object, you add sizeof(vtable ptr) to the any internal pointer, 4 on your build.
Related
The setup is I have an object and below that object is a secret pointer.
This pointer points to an object of the same class but a different object than the one above it.
I have a function that takes in the top object and uses pointer arithmetic to get the pointer that is below it.
Then inside this function I want to modify the value of the object the secret pointer is pointing to.
In debug I can see the value is being modified just fine in the function but once the function returns the value is not preserved.
I'm beyond confused why.
Any ideas?
Also I own all the memory that these objects and pointers are being created in so I don't think any heap issues should occur as I'm doing my own little memory manager for fun.
I"m thinking the issue is related to me using reinterpret_cast, if I"m right what would be a solution/alternative, and why is this the issue?
void doWork(Obj* pObj) {
// Get address of the object the pointer is pointing to
unsigned char* position = reinterpret_cast<unsigned char*>(pObj);
// 16 Bytes below the object is a secret pointer
position += (sizeof(Obj) + 16);
// Retrieve the secret pointer
Obj* secretObj = reinterpret_cast<Obj*>(position);
// Modify a value in that secret object
secretObj->value += 1;
}
I have tried the suggestions of passing the pointer in by reference and still had no luck.
I'm confused why the way the pointer is passed in would even matter at all honestly as I'm only using that pointer to get the address to use as base then I go and create a new pointer using reinterpret cast with that (address + sizeof(Obj)) and do my work on that newly created pointer.
It's because that you are passing pointer to a pointer.
The address of an address, any changes will be held locally in the scope of function only.
For solving this you should pass the pointer with reference.
void doWork(Obj* &pObj)
This should work.
The (&(*pObj)) is redundant. You are taking the address of an object you just dereferenced. Surely (&(*pObj)) == pObj?
The most likely problem is your offset calculation. Your calculation adds the size of Obj and 16. We cannot tell from your example if this is correct because you don"t give us details of Obj or how the secret pointer is defined. If this calculation is wrong, then the update to value will appear to have worked in your function but you have changed the wrong bytes so it is not seen correctly outside the function.
I have a managed C++ wrapper class for a non-managed C library. I came across an issue where it seems that the pointer I am sending from my managed C++ class is not pointing to the same memory location which is used by the non-managed C code library method.
MyNonManagedType* dataPointer;
getDataFromNonmanagedCLibrary(dataPointer);
// this gives me junk data, where field should be a char array
String^ myFieldValue = gcnew String(dataPointer->field);
Is it possible that the dataPointer is not pointing to the same address used by the C library? Or maybe there is some kind of marshal method I need to use for this, or other pitfalls I may be missing?
If the pointer is not managed, given the code you have shown, there is no way for a C function to do anything with the uninitialized pointer except either:
Check it for NULL, and if so, do nothing with it, or
Use the address passed, and disaster happens.
You are passing the pointer by value, and passing by value means that the function will be using a local copy of the parameter that is passed, thus you see no changes when the function returns. The function cannot set the pointer and have those changes reflect back to the caller the way it stands now.
Since we're talking about a C interface, you should change the C interface to this:
void getDataFromNonmanagedCLibrary(MyNonManagedType**);
A pointer to the pointer is passed. Since we want to change the value passed to the function and have it reflect back to the caller, a pointer to the value is passed. Since the value just happens to be a pointer, we pass a pointer to the pointer.
Then you rewrite getDataFromNonmanagedCLibrary to initialize the pointer by dereferencing it:
void getDataFromNonmanagedCLibrary(MyNonManagedType** ptr)
{
*ptr = <the_address_you_expected_on_return>;
}
Then on the client side:
MyNonManagedType* dataPointer;
getDataFromNonmanagedCLibrary(&dataPointer);
Note that the address of the pointer is passed, no different than if you wanted to have a function change a non-pointer variable by passing the variable's address.
I'm currently learning about virtual functions, and in this particular lesson it creates an array of object pointers firstArray[5], and calls functions from these objects. Until now, whenever I wanted to call a function func() from an object foo, I would write foo.func(). Now that I'm using virtual functions and this array, the book has switched to this method: firstArray[0]->func(). The book doesn't do a great job at justifying this switch, could someone please explain? I see that when I try to use firstArray[0].func(), I get this....
error: request for member 'func' in 'firstArray[0]', which is of non-class type 'sampleClass*'.
Is it simply because I'm trying to call a function from a pointer, not an actual object? I've been learning C++ for several months now, and for whatever reason pointers still trip me up sometimes. Any clarification would help.
EDIT:
I think the part that got me mixed up is this: I can create a pointer to a base object class with base *ptr;. Then, I can set that pointer by creating a new object from a derived class by saying ptr = new derived;. This is where I get confused. If I were to create an int* ptr;, and I wanted it to point to a integer I create, I couldn't say ptr = int j. If ptr is really just an address, why do these two examples work differently? I guess I don't understand the "new" mechanic very well either.
That doesn't have anything to do with virtual functions. If you have a pointer you need operator-> to deference and access the object it's pointing to....
You could still use the operator. (dot) to access the members/functions if you dereference first:
(*foo).func()
A pointer to an object just holds the address where the object is held in memory.
So if you have a variable which is a pointer to some type, it actually holds a number.
If you want to use the object, you need to call the object it is pointing to, which is as I said by using either operator* or operator. (dot).
A pointer that is passed-in-by-reference. Why? aren't pointers just references anyways? What's really happening to this parameter?
void someFunc(MyPtr*& Object)
{
}
Simply speaking, it gives you the ability to change the pointer itself: it can be changed to point to another location in the function.
And the change will be reflected outside.
It enable you to:
void someFunc(MyPtr*& Object)
{
//Modify what Object is pointing to
Object=&old_Object;
//You can also allocate memory, depending on your requirements
Object=new MyPtr;
//Modify the variable Object points to
*Object=another_object;
}
Other's will have to vote to verify this cause I'm a bit rusty on my C++ but I believe the idea here is you'd pass in a pointer by reference, that is instead of creating a new space to store the pointer itself you use a reference to the pointer so if you were to modify the pointer not just the value it would be modified after returning from the function, whereas otherwise all you could do is modify the value at position passed in. Hope that makes sense.
The difference to passing just a pointer is that if the pointer is changed (Object = x) then this change will be seen by the calling function. You could achieve the same when you pass MyPtr** Object and dereference the pointer *Object = x;. With the second approach you could pass NULL to the function. This is not possible for references.
You are not quite right. The pointer content is passed by reference but the pointer itself is still passed by value, i.e. reassinging it to some other pointer will not be reflected upon the exit from the method because the pointer will be set to point to the same memory block as before the call. Think of it as a simple int variable. However with &* or ** you can reassign the pointer and that will be visible outside the scope of this method.
Why?
For the same reason that you would pass in anything else by reference.
aren't pointers just references anyways?
Dear god, no. Not even remotely the same thing. Look, you can try to build a mental model of a reference by starting with a pointer, but by the time you've fixed up all the differences, you have a horrible illogical mess.
References are a much simpler and more intuitive concept, and there are only "historical reasons" for trying to understand pointers before them. Modern C++ uses raw pointers only rarely, and treats them as an implementation detail as much as possible.
A reference is another name for an already-existing thing. That's it. When used as a function parameter, they thus allow the called function to refer to the caller's data.
It also means the pointer can be 0 (NULL) which can having meaning to the method. A reference must always be valid and cannot be made 'nothing'
My program is crashing every time I try to store a COM pointer into a struct, and then later try to use the original pointer. I don't have debug access to tell exactly what's wrong.
pRend->cp = cpRT;
ID2D1SolidColorBrush *scBrush;
ERF(cpRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::CornflowerBlue), &scBrush));
It crashes on CreateSolidColorBrush. However, if I comment out pRend->cp = cpRT, it doesn't.
By the way, pRend->cp and cpRT are of type ID2D1HwndRenderTarget *.
Instead of assigning directly QI and then store i.e.,
pRend->cp = cpRT;
should be replaced with
cpRT->QueryInterface(&pRend->cp);
It's unclear how much code exists between when you assign it into the struct and later use it in CreateSolidColorBrush. If it's a non-trivial amount of time, it's possible that you have a reference counting issue.
Are you storing a raw pointer in the struct? If so, switch it to a CComPtr and see if the crash goes away.
For instance. If you had the following type definition for the value of pRend (call it Render) and the value pRend was destroyed before making the CreateSolidColorBrush call, you could see this behavior.
struct Render {
ID2D1HwndRenderTarget *pCt;
~Render() {
pCt->Release();
}
};
As it turns out, I managed to stop the crashing by allocating pRend with malloc. This is not a problem because I will call free when I don't need it anymore. I'm interested in why calling malloc fixes this though. I'm used to just doing Datatype * var; and then just using var. Is that bad?
It's a smart pointer. I'm guessing you're inadvertantly calling release on it. In particular, it's addressof operator (unary op&) is overriden to call Release().
See what happens if you instead assign it to a reference, an ID2D1HwndRenderTarget*&.
Obviously, if you assign to a reference, you won't be able to reseat it.