Check Value of .NET Handle ^ - interop

Here's my situation:
I have .NET wrapper-objects in a C++/CLI layer that hold pointers to unmanaged C++ objects. I've implemented the finalizer so that it deletes the unmanaged memory pointed to by the wrapper-object on garbage-collection and sets the pointer to null.
Here's the problem:
I'm watching the finalizer for the .NET wrapper-object and it gets called twice and tries to delete the same memory twice, indicating that I have somehow created 2 .NET wrapper objects that go out-of-scope, and are garbage collected while I'm still expecting the wrapper object to be in scope (these wrapper objects are getting passed to a VB.NET application).
Here's my question:
Is there anyway for me to check the handle value so that I can confirm where the wrapper objects are getting created (copied or whatever)? Currently I'm looking at the handle values (EG - 0x0014fe80), but I see 3 different values for when the object is created, added to a collection, and deleted. So I'm not sure if the GC is just moving stuff around and this is the same object, or if I'm actually seeing 3 different objects that reference the same unmanaged memory. I would like to resolve the duplicate object copies if possible, but I understand that I will probably want to implement some sort of smart pointer so that this doesn't happen.
Thanks,
Ian

Take a look at this question
Here is an implementation of a scoped_ptr that is noncopyable and has an auto-release mechanism for unmanaged objects, by #Ben Voigt

Yeah, I ended up modifying an auto_ptr class to be a shared pointer to ensure that the unmanaged memory is only deleted once through the smart pointer finalizer. I'm assuming I did something similar to all the other implementations; I created a static dictionary in the auto_ptr template class, using the native pointer value as the key, that is checked every time the finalizer is called to update the count of each item, or delete the memory.

Related

Call native code when a JS value is garbage collected

In my application I'm creating some JS objects, and also on C++ side some objects for running some handling.
I would like to delete C++ objects when they are not needed anymore: the corresponding JS object is Garbage Collected.
I'm trying to find that in Cobalt source code/documentation but I cannot find that. I do see ScriptValue::Reference but this seems to be the opposite:
Prevent a JS object from being garbage collected by declaring a relation between a JS value and C++ object.
Could someone give some hints how this can be achieved? (getting some callback called in C++ when an object is garbage collected).
Any C++ class exposed to JavaScript must inherit (directly or indirectly) script::Wrappable which has a virtual destructor. This destructor will be called when a corresponding JavaScript object is destroyed, either as a result of garbage collection or JS VM teardown.
Usual caveats apply: GC order and timing are non-deterministic. If you need to free critical resources as soon as possible, expose explicit cleanup methods to JavaScript.
See cobalt::dom::Node::~Node() for example of a cleanup performed upon destruction.

C++ std::unique_ptr with STL container

I got a piece of code which uses a std::set to keep a bunch of pointer.
I used this to be sure of that each pointer will present only once in my container.
Then, I heard about std::unique_ptr that ensure the pointer will exists only once in my entire code, and that's exactly what I need.
So my question is quite simple, should I change my container type to std::vector ? Or It won't changes anything leaving a std::set ?
I think the job your set is doing is probably different to unique_ptr.
Your set is likely recording some events, and ensuring that only 1 event is recorded for each object that triggers, using these terms very loosely.
An example might be tracing through a mesh and recording all the nodes that are passed through.
The objects themselves already exist and are owned elsewhere.
The purpose of unique_ptr is to ensure that there is only one owner for a dynamically allocated object, and ensure automatic destruction of the object. Your objects already have owners, they don't need new ones!

Golang new memory allocation

I have started programming in Go and I was wondering when new(Object) is used it allocates memory to the size of that object right? If this is the case how do I free this memory once I have finished using the object?
I ask this because in C++ when new is used on an object you can delete the object once there is no longer any need for the object to be stored.
I have been searching to see if Go does have delete or something similar to C++ but I have been unable to find anything.
Any help is much appreciated.
As you see here:
Go is fully garbage-collected and provides fundamental support for concurrent execution and communication.
So you don't have to care about memory allocation.
Go has garbage collection. This means the Go runtime checks in the background if an object or any other variable is not used anymore and if this is the case, frees the memory.
Also see the Go FAQ: Why is the syntax so different from C? - Why do garbage collection? Won't it be too expensive?
In Go, unlike in C and C++, but like in Java, memory is managed automatically by a garbage collector.
There is no delete to call.
Off-topic:
in C++ when new is used on an object you can delete the object once there is no longer any need for the object to be stored.
You must delete, otherwise you have memory leak.

Releasing memory in smart pointer

When we are using dynamically allocated memory, the usefulness of the delete command is obvious - we need to let our program know that the memory at the pointer is no longer needed and can be repurposed.
Smart pointers in C++11 (e.g. unique_ptr) have a member function seemingly used for a similar purpose: release(). I thought the point of using smart pointers was to avoid having to manually handle the release of memory. Why is the release() function provided when, in this context, it seems pointless?
(pun intended)
unique_ptr::release is not equivalent to calling delete on the managed pointer. unique_ptrs are used when you want a sole entity owning a heap-allocated object. unique_ptr::release relinquishes ownership and returns the raw pointer. There might be instances when you no longer want the unique_ptr to own the managed data and yet not destroy the object - maybe you want to call a legacy API which takes a plain pointer and assumes ownership of it. Or perhaps you want your interface receive a unique_ptr but have many shared_ptrs having access to it in the implementation. So, the implementation would release from the unique_ptr and transfer ownership to one or more shared_ptrs.
unique_ptr only automatically releases memory when it goes out of scope or is assigned a new pointer, but you might want to release the memory before that (the most obvious reason would be optimizing memory usage).

Safe way to generically allocate memory in Cocoa which will be automatically deallocated

In my Cocoa project I had a bunch of places where I used malloc/free. However several months ago I decided to refactor to leverage ARC and in order to do that I tried to make a replacement for malloc which will return a pointer to something that will be automatically cleaned up.
I used this function (error checking and other logging omitted)
+ (void *) MallocWithAutoCleanup: (size_t) size
{
NSMutableData * mutableData = [[NSMutableData alloc] initWithLength:size];
void * data = [mutableData mutableBytes];
return data;
}
This worked fine for awhile, but recently a random memory overwrite issue came up. I tracked down the cause to this function, what appears to be happening is the NSMutableData instance is being deallocated even though I am keeping a pointer to its mutableBytes.
I guess this is happening because the only direct reference to the object is local and is going away, and the mutableBytes points inside the object so the ARC isn't smart enough to deal with that sort of reference counting.
Is there any way I can refactor this code to retain the mutableData object as long as the mutableBytes pointer is being used (i.e. someone has a reference to it)? I know one option is to just return the NSMutableData itself, but that requires some heavy refactoring and seems very messy.
In the 10.7 SDK, -[NSMutableData mutableBytes] is decorated with the NS_RETURNS_INNER_POINTER attribute. This signals to the compiler that the method returns a pointer whose validity depends on the receiver still existing. What exactly ARC does with this is open to change, but currently it retains and autoreleases the receiver (subject to redundant operations being optimized away).
So, the pointer is valid for the duration of the current autorelease pool's lifetime. This is akin to -[NSString UTF8String] (which is decorated in the same way).
ARC is not capable of keeping the mutable data object alive so long as there's any reference to the byte pointer. ARC is not a garbage collector. It doesn't watch all uses of all pointers. It operates locally. It examines one given function, method, or block and emits retains and releases for the behavior of the code as indicated by naming conventions. (Remember that ARC is interoperable with code which hasn't been compiled with ARC support.)
Since a void* isn't an object pointer and can't be retained or released, ARC can't do anything with it. So, in the code calling your -MallocWithAutoCleanup: method, ARC doesn't see anything it can manage. It doesn't emit any special memory management code. (What could it emit at that point?) While compiling the caller, the compiler likely doesn't know anything about the method implementation or the mutable data object inside it.
Think about it another way: if you were still writing manually reference counting code, what would you do in the caller of your method to keep the pointer valid? For the most part (ignoring __weak references), all ARC does is automatically do what you would do manually. Once you consider that you would have no options in that case, you realize that neither does ARC.
I think you answered your own question. If you want to use NSData to manage generic memory allocations, you need to keep a reference to the NSData objects around until you're done with the memory it owns, at which point you nil out your reference(s) to the NSData object in question. This doesn't seem to provide any advantage compared to just manually freeing the malloced memory. Personally, I'd continue to use malloc()/free() explicitly instead of trying to contort my code in such a way that ARC kind of sort of manages malloced memory.
Either that, or I'd write my code such that it doesn't have to use malloc/free in the first place. I'd say the typical "pure" Cocoa project doesn't have many, if any, explicit malloc() calls, and I'd be a little suspicious of code that did unless there was some good reason for it. Why are you using malloc() in the first place?

Resources