C++/CLI - Help with pin_ptr - managed-c++

I'm writing a wrapper app that uses some unmanaged functions and I'm using a lot of pin_ptr.
My question is, most of the time I use pin_ptr inside a method call, and the pin_ptr variable is declared also inside the method call. When the code goes our of the method, can I have any problem because it's no longer pinned? Should I move the declaration to a class scope?
thanks!

The only time you need to pin an object on the managed heap is when an unmanaged function or unmanaged code directly accesses the object in memory (such as through a pointer). If when your method exits, nothing is currently accessing the object's memory, it can be unpinned (as long as you pin it again before directly accessing it the next time).

Related

Passing object via Qt signal/slot across threads

I wish to pass an object using the signal/slot mechanism between threads in Qt. Since I will be passing a pointer to the object, is it safe to call the methods on the object on the receiver's side?
According to this question question the object is not copied (so using original object).
Is this safe? Or am I executing methods on an object belonging to one thread in another thread? Is there a better way to do this?
(I have approximately 20 getters in this class so I don't want to pass individual variables, as well some of the variables are in fact pointers to objects as well)
It is not necessarily safe - signals and slots can be used to cross thread boundaries, so it's possible you could end up trying to access the object from another thread.
The thread in which the slot will be called is determined by the connection type. See the documentation, but as an example:
connect(source, SIGNAL(mySignal(QObject*)), destination, SLOT(mySlot(QObject*)), Qt::DirectConnection);
In this case the function mySlot() will be called from the same thread that the mySignal() signal was emitted in. If your object is not accessed from any threads other than the same thread as the signal emitter this would work fine.
connect(source, SIGNAL(mySignal(QObject*)), destination, SLOT(mySlot(QObject*)), Qt::QueuedConnection);
In this case the function mySlot() will be queued, and called by the event loop of the destination object. So anything done to the object, would happen from within the thread running the event loop of the destination.
I personally find it's best to just stick to passing simple values as arguments. Even though this can work, you would need to add suitable multithreading guards to your QObject if it's likely to be accessed from multiple threads.
First of all, try to use QtConcurrent when you are developing a multi-threaded application. The QtConcurrent namespace provides high-level APIs that make it possible to write multi-threaded programs without using low-level threading primitives such as mutexes, read-write locks, wait conditions, or semaphores.
After that, safety depends on your class members. If all members are thread-safe, then all will be run safely.

Converting from String^ to String*

I'm currently having a small issue which i thought would be easy, but not, so,(maybe it is easy, but i don't know) i need to convert a String^ into a String^* so basically a string pointer, small snippet of code:
ARPLC_command_byuser = textBox1->Text;
I've already tried various of methods, but all seem to fail(well, they don't, i do).
If you have any idea, please tell me what to do.
That's not possible. A managed object is moved around in memory when the garbage collector compacts the heap. Which will invalidate any pointer. This is the primary reason that C++/CLI uses the ^ hat to indicate object references, they are pointers under the hood that the garbage collector can recognize and update when the object is moved.
Technically it is possible to pin a managed object to ensure that it doesn't get moved. Something you can do with pin_ptr<> or GCHandle::Alloc(). This should be avoided. Convert the managed string to a native pointer by copying it into unmanaged memory using the Marshal class.

The cross-thread usage of "HttpContext.Current" property and related things

I read from < Essential ASP.NET with Examples in C# > the following statement:
Another useful property to know about is the static Current property
of the HttpContext class. This property always points to the current
instance of the HttpContext class for the request being serviced. This
can be convenient if you are writing helper classes that will be used
from pages or other pipeline classes and may need to access the
context for whatever reason. By using the static Current property to
retrieve the context, you can avoid passing a reference to it to
helper classes. For example, the class shown in Listing 4-1 uses the
Current property of the context to access the QueryString and print
something to the current response buffer. Note that for this static
property to be correctly initialized, the caller must be executing on
the original request thread, so if you have spawned additional threads
to perform work during a request, you must take care to provide access
to the context class yourself.
I am wondering about the root cause of the bold part, and one thing leads to another, here is my thoughts:
We know that a process can have multiple threads. Each of these threads have their own stacks, respectively. These threads also have access to a shared memory area, the heap.
The stack then, as I understand it, is kind of where all the context for that thread is stored. For a thread to access something in the heap it must use a pointer, and the pointer is stored on its stack.
So when we make some cross-thread calls, we must make sure that all the necessary context info is passed from the caller thread's stack to the callee thread's stack.
But I am not quite sure if I made any mistake.
Any comments will be deeply appreciated.
Thanks.
ADD
Here the stack is limited to user stack.
There are four things working together to cause the behavior you are asking about:
HttpContext is an instance object whose reference can be found in HttpContext.Current
Thread is also an instance object whose reference can be found in Thread.CurrentThread
Thread.CurrentThread is static but references a different Thread object in every thread
HttpContext.Current actually points to Thread.CurrentThread.ExecutionContext.IllogicalCallContext.HostContext
Conclusions we can draw from the above givens:
Because HttpContext is an instance object and not static we need its reference to access it
Because HttpContext.Current actually points to a property on Thread.CurrentThread, changing Thread.CurrentThread to a different object will likely change HttpContext.Current
Because Thread.CurrentThread' changes when switching threads, HttpContext.Current also changes when switching threads (in this case HttpContext.Current becomes null).
Bringing this all together, what causes HttpContext.Current to not work in a new Thread? The Thread.CurrentThread reference change, which happens when switching threads, changes the HttpContext.Current reference, which prevents us from getting to the HttpContext instance we want.
To reiterate, the only magic thing going on here is Thread.CurrentThread referencing a different object in every Thread. HttpContext works just like any other instance object. Since threads in the same AppDomain can reference the same objects, all we have to do is pass a reference for HttpContext to our new thread. There is no context info to load or anything like that. (there are some fairly serious potential gotchas with passing around HttpContext to other threads but nothing to prevent you from doing it).
A few final side notes I came across while researching:
In some cases a Thread's ExecutionContext is 'flowed' (copied) from one Thread to another. Why then is HttpContext not 'flowed' to our new Thread? Because HttpContext doesn't implement the ILogicalThreadAffinative interface. A class stored in the ExecutionContext is only flowed if it implements ILogicalThreadAffinative.
How does ASP.NET move HttpContext from Thread to Thread (Thread-Agility) if it isn't flowed? I'm not entirely sure, but it looks like it might pass it in HttpApplication.OnThreadEnter().
I think I've found a suitable explanation here: http://odetocode.com/articles/112.aspx
To summarize, the code-behind of HttpContext.Current looks like this:
public static HttpContext get_Current()
{
return (CallContext.GetData("HtCt") as HttpContext);
}
with CallContext functioning as thread-local storage (i.e. each thread will see a different copy of the data and cannot access the copies seen by other threads). Hence, once the current context is initialized on one thread, subsequent accesses by other threads will result in a NullReferenceException, since the property is thread-local to the initial thread.
So yes, your initial explanation was close, in the sense that it is a problem of data being visible only to a single thread.
The backing field of Current is marked as ThreadStatic (I assume), hence it wont be available/initialized in user-created threads.
What it comes down to is, that you should capture the instance of HttpContext.Current in the request thread and then use that instance in your threads, instead of referring to HttpContext.Current.

Should non-QObject derived classes "always" be put on the stack?

Coming from the Symbian world, I'm used to using the heap as much as possible to avoid running out of stack space, especially when handling descriptors. CBase derived classes were always dynamically allocated on the heap, since if they were not, their member variables would stay uninitialized. Does the same convention apply to QObject-derived classes?
In Qt it seems to be common to put, for example QString, on the stack. Are the string contents put on the heap while QString acts as a container on the stack, or is everything put on the stack?
As sje397 said: It's idiomatic to put QString and containers on the stack, as they are implicitly shared. Their internals (pimpl idiom "d" pointer) are created on the heap. There is no point in creating the object itself on the heap, too. Just causes memory-management hassles and you lose the intended copy-on-write properties when passing pointers to strings/containers around.
QObjects on the other hand you want to create on the heap in almost all cases, as otherwise they would be destructed again right away. They can't be copied or assigned (well, one can enforce it for own subclasses, but the QObject semantics are broken then), and usually they are supposed to survive the method body they are created in.
Exception is QDialog, which is often created on the stack, followed by QDialog::exec, which blocks until the dialog is closed. But even that is strictly spoken unsafe, as external events (RPC calls, background operations) could cause the dialog to be deleted by its parent (if the parent itself is deleted) before exec returns.
Then having the dialog created on the stack will cause double deletion when unwinding the stack -> crash.
QString, and many other Qt classes, use implicit data sharing. That implies that memory is generally allocated on the heap.

How to spot memory leaks in profiler?

I have an AIR/Flex app I made, I have a few people testing it and everyone is reporting that after leaving it running for a while, it is making all there machines run very slow. It runs fine at first so this must be a memory leak somewhere. I used the profiler on this and the only thing that shows as using a substantial amount of memory is MethodQueueElement which is not a class I wrote, and I have no idea what it does, I am assuming its part of the Flex framework. I am not familiar with using a profiler so I am not sure what all I shuld be looking at, that was the only class that was high on "memory" and it said it had over 100,000 instances. If this is my problem what can I do to fix it? I do not even know what this class does or anything about how it gets instantiated.
Thanks
The MethodQueueElement class is an internal class of the mx.core.UIComponent class.
It is used to represent on method call that has been enqueued by a callLater call.
The callLater method is part of the public interface of UIComponent, so either you call it in your code, or it is beeing called by the framework (as it happens in UIComponent.setFocus e.g.)
To free all MethodQueueElement instances, UIComponent replaces the current array of MethodQueueElements by a new (empty) one. (in the callLaterDispatcher2 method) So the only way to make a memory leak out of it is, to prevent callLaterDispatcher2 from beeing called.
To debug this, you can start to set breakpoints (while you app is running) in the methods callLater (here your instances get created, so somehow it gets called all the time, look at the stacktrace here!), callLaterDispatcher2 (i suppose it wont get called), and check whether UIComponentGlobals.callLaterSuspendCount is != 0, which could be the reason callLaterDispatcher2 doesn't get called.
Should the latter be the case, i suspect, that you have tweens or something else calling UIComponent.suspendBackgroundProcessing but then not calling resumeBackgroundProcessing (because of an exception terminating the code before reaching the resumeBackgroundProcessing call e.g.)

Resources