Posts

Showing posts from May, 2011

C# using PInvoke to call an unmanaged DLL

Recently I've found myself having to do some pinvoking with .net. Microsoft offers an excellent primer on the subject. http://msdn.microsoft.com/en-us/library/aa288468(v=vs.71).aspx For it's many great benefits the .net framework doesn't do everything. You will find yourself having to invoke a win32 API function call at some point in your career. I'm going to offer some quick and dirty samples on getting data back and forth using the platform invoke. First you cannot invoke any classes using pinvoke. You get 1 function call at a time. If you want classes you will need to write a custom CLI/C++ wrapper. But that goes beyond the scope of this post. First let's look at the unmanaged\win32 side of things. Let's say you have a dll called MyDll.dll. In this dll you have a bunch of functions. // this lets use export functions from the dll #define DllExport __declspec( dllexport ) // first we use extern "C" so we don't get name mang...

C# More on threading, killing a thread, waiting for, or how to do a Thread.Join

Image
In my last post I used a ThreadPool to do some work. ThreadPools are great and I use them a lot. However many times I find myself really only needing 1 thread and I need to have some control over it. I may need to wait for it to finish, or more importantly I need to be able to control when it dies or completes its task. For this case I always use Thread.Join As usual please peruse the MSDN documentation . Thread.Join waits for the thread to complete before proceeding with any other operations. So simply creating a thread then calling Thread.Join can be useful in some UI operations I tend to not call Join until I'm ready to kill the thread entirely. The MSDN link above goes over the great details. Now let's go over some quick code. This example creates a thread then waits for the user to press a key and terminates the thread. Let's look at the main console code using System; using System.Collections.Generic; using System.Text; using System.Threading; namesp...