Tag Archives: C++

Old C++ Code

I was inspired by a recent post by Brent Simmons to write about some ancient C++ code I wrote back in the min-90’s. At that time I was just learning to develop Windows applications in C and C++ was just starting to get some traction, not unlike Swift in the Mac and iOS community today.

When you created a Windows application you’d have to write a WindowProc (Windows Procedure) that would process all messages for a particular window. A Window Proc would receive a message and other parameters. You’d switch on the message and the WPARAM and LPARAM parameters would contain other information specific to a particular message. It was well documented, but it was quite ugly.


Believe it or not this is how a lot of your favorite Windows applications were originally written. Giant switch statements that dissected two other values to determine how to respond to different types of messages.

When I started learning C++ I was trying to find a way to create a Window Proc that didn’t have to implement every Windows message in the system, there must be thousands of them. Could you imagine a base C++ class that responded to every Windows API message in the system? I can’t. It would be a real mess to deal with.

It took me quite a while to come up with a way to do it. I happened upon the answer in the C++ FAQ. This would allow me to create a base class that provided one Window Proc that would look in a dispatch table (a map) to see if the Windows Message was handled by the Window in question.

Here’s what it looked like. I hope this gets the point across.


When you implemented a Window Proc class you would derive from a base class and provide it with a message dispatch table (at the top of the above gist.) The dispatch table would direct the base classes Window Proc to call the correct handler for a specific message.


Notice that this Window Proc is a straight C function. That’s how the Windows API operates. It’s a C based API, but it provides a mechanism to attach user provided data to a Window Procedure. That’s how this operates. When the Windows WM_CREATE message is sent it includes a this pointer to derived Window Class, which can be looked up later based on the HWND identifier.

In the gist above the code that calls pWindow->DispatchMessage knows how to look at the dispatch table and direct the message to the appropriate pointer to a method.


The code that knows how to send a message to a particular method is (this->*pHandler)(wParam, lParam). This is dereferencing a pointer to a method. All methods have the same signature, which is consistent with how the Windows API works.

Will Code C++ for Food
By the way. This code still builds and runs with up to date versions of Visual Studio on Windows 10. A lot of this code was written in 1995 and has been tweaked over time to keep it up to date with changes to the Windows API.

As I’ve said before, old code never dies.

If you’re feeling really brave you’re welcome to grab my crusty old C++ library and build the simple sample application on your Windows box. Please note, the code is provided as is without warranty, expressed or implied.

Mobile Cross Platform in C++

Will write C/C++ for foodPSPDFKit Blog: “PSPDFKit started in 2010 as an iOS-only project. Back then there was just one person working on it. 6 years later, we’re 28 people, have frameworks for iOS, Android and the Web, and our core framework even runs on OS X and Windows.”

Great piece on cross platform development using C++ and a tool from Dropbox called Djinni to help make things look native.

I’ve been toying with the idea of making RxCalc run on Android and the first thing I want to do is rewrite our Pharmacokinetics Math Library (PkMath) in C++, which ironically began life in C++ and was ported to Objective-C.

Native Development on Windows

Yesterday I asked on Twitter…

I got one serious answer and some fun poked at the question, which is fine, but I think it points to a real problem on the Windows Desktop. 

Has Microsoft given up on native applications at a time when native on Apple Platforms and Android have never been more popular?

On Apple Platforms we have clear, well defined, native development tools for creating serious desktop applications. Think of apps like Photoshop, or more modern takes on graphics like Sketch, Acorn, Pixelmator, or OmniGraffle. Most of these applications are written in Objective-C against Cocoa (Apple’s Framework for writing applications.) Sure, Photoshop is the old guy in the mix and is built on a custom framework written in C++ that communicates down to Cocoa (and possibly some Carbon API’s?) also worth noting, with the exception of Photoshop, not a single app mentioned above is cross platform (I’m not including Mac to iOS as cross platform, many of the API’s are the same and the act of going from one to the other is much easier than going to a completely different platform.)

All that brings me back to the question of developing native applications in the vein of Visio or Photoshop on the Windows Desktop. I’ve seen plenty of talk about creating Universal Apps, but those seem geared toward a lighter weight style of application, singular purpose apps focused on lightweight tasks, like Twitter or Facebooks clients, not hard core productivity applications that need to perform well and provide their best experience on the Desktop.

We still have Visual Studio, C++, and the Windows API, as a development platform but it feels somewhat abandoned. I know the folks working on the C++ compiler would probably argue against that statement because Microsoft is definitely investing in C++, but what about OS level API’s? That is the level that sort of feels abandoned. We have WinRT today, which seems like it might be part of the story for native desktop development, but do you mix and match that with the Windows API to build a great native application, do you use WinRT alone, or do you just continue to plug away with the Windows API?

It seems that apps built for the modern Metro look should use WinRT? Based on that it seems the old tried and try combination of C++ and the Windows API would still be the best choice for hard core desktop development.

But what about C# and XAML? Maybe those are a good choice for serious desktop development? I’m unclear on that subject. I’ve heard that the Visual Studio IDE was rewritten in C# for Visual Studion 2012, but I don’t know if that’s true or not. If someone reads this post and can point to MS Office, Visual studio, or Photoshop class applications written in C#/.NET I’d love to hear about them. Worth noting is the wonderful toolset by the folks at Xamarin, it makes C#/.NET app development truly cross platform.

Being a long time C++/Windows API guy I still gravitate toward that toolset. Hey, I have a lightweight class library I wrote in 1993-94 that still works today; it builds with Visual Studio 2015 and runs fine on Windows 10, but it could certainly use some refactoring given the state of modern C++. Think C++14.

I’ve been working on a cross platform project recently using Qt, which has me think about portable C++ for Mac, iOS, Windows, and Android. Given C++14 as a starting point for most OS level services; file I/O, threading and synchronization, etc, what would it take to build a modern C++ library that handled native user interface creation and interaction and didn’t feel too constraining on the platform? Remember, most cross platform tools come at a price. They’re always a little behind, they tend to be least common denominator, and can feel non-native. Qt, for instance, doesn’t use native controls on Windows (NOTE: this may not be true today. This was true around 2008, the last time I looked), I find that terribly annoying. I’m sure any Mac, iOS, or Android developer worth their salt would also find it annoying. 

A nice new C++ framework for building native OS level user interfaces using modern C++ as a base would be great to see. I really wonder how long it would take to build such a thing?

Old Code Never Dies

CheezyPing still worksI happened across some old C++ code I wrote back in 2001. I decided to put it up on GitHub for kicks, might as well put some history up for future generations, right?

I was curious to see if I could build it. The original project was built with Visual Studio 6.0, circa 1998. I have a copy of Visual Studio 2010, so I fired it up pointed it at the original cp.dsw file and was pleasantly surprised it converted. I selected Build All and got a few warnings about some ATL include files I no longer needed, so I removed those. The only other thing that needs correcting are a few warnings related to use of older CRT string copy functions that are not secure. If you’ve upgraded a C or C++ project over the last few years you’ll be familiar with this warning:

warning C4996: '_tcsncpy': This function or variable may be unsafe. Consider using _tcsncpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

The code still builds and will execute, but if I were going to use it daily, I’d update it. For now, it’s OK, the code built. Maybe I’ll download a new copy of Visual Studio 2013, get it working with that, and check it in. It would be pretty nifty to create a Mac version by doing an implementation of the HttpIf interface using NSURL and NSURLConnection. This could be a GrilledCheese implementation. Hmmmmmm.

Anywho, once I got a build I hopped out to the command line, and ran it. I was surprised to see, it still works. Amazing.

Pelco SDK 3.3.1 – Collecting Devices C++ Sample


By day I’m the Development Lead for a small group of folks responsible for the Pelco SDK. This post is not an official Pelco article, just something I wanted to share.


Last August I rejoined Pelco to help design a new object oriented version of the SDK and that’s what we’ve been doing for the last year plus. We’ve released four revisions of the SDK over that time period and are working on our fifth.

Something I’ve wanted to share for a very long time is how simple it is to work with our new Object Model to collect devices and play video. We’ve simplified the entire process. The original version of the SDK evolved from need, as a lot of things do, but over time it becomes more and more difficult to maintain and enhance that code without breaking backward compatibility. In the new Object Model we’ve worked very hard to make it easy and give you the power you need to code new solutions and give us a platform to build on in the future.

I plan on sharing a sample application after a very brief overview of our Object Model. The application, called EnumDevices, is a C++ application. You can find it on GitHub. I’d be happy to create the same application in C#/.Net. If you’re interested get in touch, rob@crabapples.net.


The Object Model is pretty simple, here are a few objects, just to get us started. You can view the entire list on PDN(it’s a PDF file.)

  1. SystemCollection
  2. System
  3. DeviceCollection
  4. Device
  5. Camera
  6. Display
  7. Stream

Of those we’ll discuss System, DeviceCollection, and Device in the sample. There is some boilerplate code you’ll need to write, but we’ll skip that for now, so we can get on with the sample. Look at main() in the EnumDevices sample, the boilerplate happens prior to calling the EnumDevices function. Something to note. This sample uses version 3.3.1 of the SDK, which introduced an explicit Startup() and Shutdown() function, keep that in mind if you’re using version 3.0 through 3.3, these functions don’t exist in those releases.

EnumDevices C++ Sample

On to the sample code. If you haven’t grabbed the code yet, head over to GitHub and pull it down, I’ll wait.

Some things to note about the sample code. It’s only available for Visual Studio 2010. Our SDK only supports Visual Studio 2008 and Visual Studio 2010 for the time being. I have no idea how it will behave in Visual Studio 2012 or Visual Studio 2013.

Ok, on with the code. We’re going to focus on one function in the sample; EnumDevices. This little bit of code will add, or get, a System, get the DeviceCollection and enumerate it. As it does it will print out the Device Friendly Name. That’s it.

Here’s the code, we’ll break it down below.

static void EnumDevices()
        // Create or get an existing system
        PelcoSDK::System system("admin:admin@pelcosystem://[insert your ip and port here]?alias=Enum Devices Sample System");

        // Get the Device Collection from the system
        PelcoSDK::DeviceCollection devices(system.GetDeviceCollection());

        // Iterate over the DeviceCollection and print out the device friendly name.
        while (devices.MoveNext())
                PelcoSDK::Device device(devices.Current());
                printf("Device Friendly Name: %s\n", device.GetFriendlyName().c_str());


Dissecting the code. I’m sure the first line of code, where we create the System, will have folks asking questions. When we were trying to decide our model for creation and access of Systems we wanted to make it as easy as possible and provide a great deal of power without forcing the user to jump through a lot of hoops. In the end it was decided we’d fashion it after a URI Scheme. Today most people know what a web address looks like.

Here’s the line of code in question:

PelcoSDK::System system("admin:admin@pelcosystem://");

The interesting portion of that line is "admin:admin@pelcosystem://". In our scheme “pelcosystem” represents the scheme name, we’ve put the username and password information to the left of the scheme, before the @. Following the :// is the host name, followed by the port, and a query string. We use the query string for arguments, in this example we’re assigning an alias name to the System so we can use that to look it up later, or display it in our user interface.

Something else to note about the use of the scheme in the sample. It serves to do the initial add of the System to the SystemCollection and works to look the System up later, without going to the SystemCollection. Our sample could have also added the System to the SystemCollection by using the Add method directly on the SystemCollection, but it’s not required. That said, the first time you run this code it will be a bit slower than subsequent runs. The first time through the System and all its devices will be added to a local device cache so the next time you startup will be much quicker.


The second line of code is pretty straight forward. After we’ve created, or retrieved, a System we’d like to get the DeviceCollection so we can do something interesting. Maybe we’d like to populate a tree control with a list of devices, or just dump out device information to a simple console application, like this sample.

PelcoSDK::DeviceCollection devices(system.GetDeviceCollection());

There’s not a lot to talk about here. We’re constructing a C++ object of type PelcoSDK::DeviceCollection using the results of a call to system.GetDeviceCollection(). Now we have a DeviceCollection Object we can enumerate.

All of the collection classes in the SDK implement an interface called IEnumerator, it’s a template class that exposes three methods; Current, MoveNext, and Reset. These methods make it really easy to iterate all collections in the SDK with a simple while loop.

while (devices.MoveNext())
	PelcoSDK::Device device(devices.Current());
    printf("Device Friendly Name: %s\n", device.GetFriendlyName().c_str());

After getting our collection it should be in a “reset” state, but the first line of code above shows how to reset the internal iterator back to the beginning of the collection. Notice the while loop checks the result of the devices.MoveNext(). The MoveNext method will move the iterator to the next item in the collection and returns a boolean value, true if it has a next device, false if it doesn’t. Once there are no longer devices in the collection we’ll break out of the loop.

If we do have a device in the collection you can retrieve it by asking the DeviceCollection for its Current() object. Since IEnumerator is a C++ template the type of object returned is a PelcoSDK::Device. You can read more about the Device Object on the Pelco Developer Network(PDN).


Hopefully this sheds a bit of light on the direction of the Pelco SDK. We’re off to a nice start, but we have a long way to go, and we’d love to hear back from developers and partners. Please, reach out. Let us know how we’re doing, where we need to improve, and share your stories.

Until next time, happy coding.

Mike Ash on Objective-C Blocks

Duct Tape, fixer of all things!Mike Ash: “Both Objective-C blocks and C++0x lambdas have the same basic goal: to allow writing anonymous inline functions. Called closures, blocks, lambdas, or just anonymous functions, these are a common feature in higher level languages. They are extremely useful for building convenient, succinct libraries for things like array iteration, multithreading, delayed computation, and many others.”

Mike explores Objective-C Blocks and C++ Lambdas. This article is six months old, but it’s still very relevant and great as always. If you’re a Cocoa Head you should definitely add Mike’s RSS feed to your preferred news reader.

T.T.F.N LEVEL, I Still ♥ You

It’s true. Today is my last day with LEVEL Studios. It’s hard to say goodbye to a place like this, especially when you do love her and her people. It’s been a fun year, but it’s time for me to move on.


That’s the hard part to explain, because I really do love this company. It’s full of smart, energetic, people. It has a great company culture and fantastic leadership. The “problem” falls squarely with me.

They're bouncy, bouncy, bouncy, bouncy, bouncy, fun, fun, fun, fun, fun...Anyone who knows me knows how much I love the native client experience. I’ve had the honor to work with a team that created a new segment in Windows drawing applications and I’ve worked on native iOS applications and I LOVE that experience. I think User Experience, or UX, is so important and I believe the best way to provide that important experience is through native API’s provided by the platform vendor. So, yes, I’m going back to writing desktop software. No, it’s not on the Mac, or iOS, even though I’d love to do that. I’m going back to writing Windows software. That’s right, back to C++ and Windows! I can see my fellow LEVEL’ites rolling their eyes. That’s ok, I likes me some native clients. It’s in my blood.


Where is a great question. We’re staying in San Luis Obispo, we don’t plan on leaving this place. I’m going to work for a company called CygNet. They’re a product company. From the CygNet website.

CygNet Software provides enterprise software and industry solutions that collect, manage and distribute essential operations data. Robust, proven and evergreen, CygNet extends customer horizons with improved operational efficiency and increased market responsiveness

I’ll be working on products used to collect and analyze data from Oil and Gas Pipelines, and I get to work on UI again! Yes, I’m pretty stoked about it!

On the LEVEL

LEVEL is a definite powerhouse when it comes to the web. In fact I’d encourage young up-and-coming web developers or designers to consider LEVEL as a place to start your career. You’ll learn loads. LEVEL is chock full of great web developers, not to mention fantastic designers.

A wonderful boquet of flowers.Oh, yeah, and there’s this great group of folks, they keep in a dark room, that develop great, high performance, highly scalable, web services. One of our web services is serving near four million users worldwide, and growing every day. Yes, LEVEL can build these things. Shhhhhh, keep that under your hat, it’s a secret!

Would I work here again? Absolutely. That’s what made this decision so tough.


I don’t believe in saying Goodbye, goodbye is forever. I’ll just say TTFN *Le Publetta.

*Le Publetta is a combination of LEVEL, Publicis, and Rosetta. I think it’s a strong name, don’t you?

Why derive a C++ class from a struct?

This question came up on Twitter yesterday, and got me thinking. Yeah, why would you do that? The only answer that sprang to mind was for compatibility reasons. If you have the luxury of working on a modern codebase you may not do this sort of thing, but if you have a legacy application or are working with a legacy API you may have need to call C functions that take structs and you may want to manipulate those structs in your C++ code, but do it in a C++ way. Make sense?

Here’s what I’m talking about. Take this C struct for example.

typedef struct tagABC
	int      a;
	long     b;
	float    c;
} ABC;

Back in the day, when the ABC structure was created, the developer also created a function to operate on this structure, something like this…

float OldSchoolCDoFancyCalculation(ABC* abc)
	return ((float)abc->a+(float)abc->b+abc->c);

That looks pretty darned straight forward. The OldSchoolCDoFancyCalculation() function takes a pointer to an ABC struct, sums the field values, and returns the result. Not uncommon. Here’s how it could be used.

	// Old school C style.
	ABC abc;
	abc.a = 10;
	abc.b = 99;
	abc.c = 99.99;

	float value = OldSchoolCDoFancyCalculation(&abc);
	printf("Old School C Struct + C Function == %f\n", value);

Moving on

Let’s say your team has decided to embrace C++ but you don’t want to go back and rewrite a bunch of code, and moving forward you’d like to make use of the nice stuff C++ has to offer. Someone may choose to do something like this with your ABC struct. I say may choose because they may do something totally different, this was the only real example I could think of, so it fits for illustration purposes.

class ABCObject :
	public ABC
	ABCObject(int aa, long bb, float cc);
	virtual ~ABCObject();

	void DoFancyCalculation();
	void PrintValue();

	float _value;
}; // ABCObject

Take note. ABCObject is derived from the struct ABC. Yes, of course you can do this in C++. When C++ was being defined this was one of those things that had to be addressed for backward compatibility with C. By default all struct members/fields have public access.

This will allow you to mix instances of ABCObject with the old C functions that operate on ABC structs. Here’s how that would look, and it’s perfectly legitimate.

	// New school C++ style, using old school C code, no problem.
	ABCObject abcObj(11, 100, 100.09);
	float value2 = OldSchoolCDoFancyCalculation(&abcObj);
	printf("New School C++ Object + C Function == %f\n", value2);

Notice we’re passing a pointer an instance of an ABCObject. What the? Sure, you can do that. It’s perfectly legal because ABCObject is derived from the ABC struct. The compiler would notice the function takes an argument of ABC* and ABCObject just happens to fit the “is-a” rule, so it can be passed as an ABC* to the function where it can be operated on like a standard ABC struct pointer.

Like I said, someone could do that. You probably wouldn’t, but the point is you could, and some folks will definitely have need to write code that looks similar to this for some very good reason. More often than not most developers would probably choose to wrap an instance of the old ABC struct as a member variable of the class and then just operate on that from within class methods.