Showing posts with label C/Cpp. Show all posts
Showing posts with label C/Cpp. Show all posts

Thursday, February 14, 2013

Reading version from EXE and DLL files

Here’s a C++ and Win32 class to read version information from the resource section within EXE and DLL Windows binaries. The key functions are GetFileVersionInfo and VerQueryValue. The object will provide public pointers to the strings; these pointers should not be deleted, since they point straight into the allocated data block. If version information can’t be read – for example, if it’s a file with no version information – the load method will simply return false.

There’s room for more improvements, like tighter error checking, but it’s pretty usable:
#include <Windows.h>
#pragma comment(lib, "Version.lib")

class VersionInfo {
public:
	const wchar_t *pComments, *pCompanyName, *pLegalCopyright, *pProductVersion;

	VersionInfo() : _data(NULL),
		pComments(NULL), pCompanyName(NULL),
		pLegalCopyright(NULL), pProductVersion(NULL) { }

	~VersionInfo() {
		if(_data) free(_data);
	}

	bool load(const wchar_t *path) {
		DWORD szVer = 0;
		if(!(szVer = GetFileVersionInfoSize(path, &szVer)))
			return false;
		_data = (BYTE*)malloc(sizeof(BYTE) * szVer);
		if(!GetFileVersionInfo(path, 0, szVer, _data))
			return false;

		UINT len = 0;
		VerQueryValue(_data, L"\\StringFileInfo\\040904b0\\Comments",
			(void**)&pComments, &len);
		VerQueryValue(_data, L"\\StringFileInfo\\040904b0\\CompanyName",
			(void**)&pCompanyName, &len);
		VerQueryValue(_data, L"\\StringFileInfo\\040904b0\\LegalCopyright",
			(void**)&pLegalCopyright, &len);
		VerQueryValue(_data, L"\\StringFileInfo\\040904b0\\ProductVersion",
			(void**)&pProductVersion, &len);
		return true;
	}

private:
	BYTE *_data;
};
Usage example:
{
	VersionInfo vi;
	if(vi.load(L"C:\\Program.exe")) {
		OutputDebugString(vi.pProductVersion);
		OutputDebugString(vi.pComments);
	}
}
Can’t be simpler than that.

Sunday, December 2, 2012

Automation for C++ COM pointers

This week I was working on a C++ program which used a lot of COM pointers. I remembered I’ve seen an automation class somewhere, and after some searching I found it, it’s Microsoft’s ComPtr template class. Although I liked the concept, it had too much fuss to me, so I was displeased in using it.

Oh well, here we go again: I wrote my own COM pointer automation class. Here it goes the full code of it, which I now share with the world:
#pragma once
#include <Windows.h>
#include <ObjBase.h>

template<typename T> class ComPtr {
public:
	ComPtr()                    : _ptr(NULL) { }
	ComPtr(const ComPtr& other) : _ptr(NULL) { operator=(other); }
	~ComPtr()                   { this->release(); }
	ComPtr& operator=(const ComPtr& other) {
		if(this != &other) {
			this->~ComPtr();
			_ptr = other._ptr;
			if(_ptr) _ptr->AddRef();
		}
		return *this;
	}
	void release() {
		if(_ptr) {
			_ptr->Release();
			_ptr = NULL;
		}
	}
	bool coCreateInstance(REFCLSID rclsid) {
		return _ptr ? false :
			SUCCEEDED(::CoCreateInstance(rclsid, 0, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&_ptr)));
	}
	bool coCreateInstance(REFCLSID rclsid, REFIID riid) {
		return _ptr ? false :
			SUCCEEDED(::CoCreateInstance(rclsid, 0, CLSCTX_INPROC_SERVER, riid, (void**)&_ptr));
	}
	template<typename COM_INTERFACE> bool queryInterface(REFIID riid, COM_INTERFACE **comPtr) {
		return !_ptr ? false :
			SUCCEEDED(_ptr->QueryInterface(riid, (void**)comPtr));
	}
	bool isNull() const { return _ptr == NULL; }
	T&   operator*()    { return *_ptr; }
	T*   operator->()   { return _ptr; }
	T**  operator&()    { return &_ptr; }
	operator T*() const { return _ptr; }
private:
	T *_ptr;
};
Basically, by using this class I don’t have to worry about calling the Release method. Most interestingly, I added two shorhand methods to ease my life, coCreateInstance and queryInterface. Here are an example illustrating the use of the ComPtr class, along with the cited methods:
{
	ComPtr<IGraphBuilder> graph;
	if(!graph.coCreateInstance(CLSID_FilterGraph))
		OutputDebugString(L"Failed!");

	ComPtr<IMediaControl> mediaCtrl;
	if(!graph.queryInterface(IID_IMediaControl, &mediaCtrl))
		OutputDebugString(L"Failed!");

	graph->RenderFile(L"foo.avi", NULL); // sweet!
}
If you’re wondering about the usefulness of this ComPtr class, try to write the code above without it.

Wednesday, September 12, 2012

Singly linked list in C++

These days I needed a clean implementation of a singly linked list in C++. I found some ones around, but none of them was functional and clean and the same time. So I wrote my own, using nothing but pure C++ with templates, and here I’m publishing the full implementation.

First, the header. I chose to put the node class nested into the linked list class, because this approach allows me to have another node class which can belong to another kind of structure, if I need to. There are a couple of methods beyond the basics, I needed them to have a functional data structure that worked for me.
template<typename T> class LinkedList {
public:
	class Node {
	public:
		      Node()                     : _next(NULL) { }
		      Node(const T& data)        : _data(data), _next(NULL) { }
		Node* insertAfter();
		Node* insertAfter(const T& data) { return &(*this->insertAfter() = data); }
		Node* removeAfter();
		T&    data()                     { return _data; }
		Node& operator=(const T& data)   { this->_data = data; return *this; }
		Node* next(int howMany=1);
		int   countAfter() const;
	private:
		T     _data;
		Node *_next;
	friend class LinkedList;
	};

public:
	      LinkedList()          : _first(NULL) { }
	     ~LinkedList();
	int   count() const         { return !this->_first ? 0 : this->_first->countAfter() + 1; }
	Node* operator[](int index) { return !this->_first ? NULL : this->_first->next(index); }
	Node* append();
	Node* append(const T& data) { return &(*this->append() = data); }
	void  removeFirst();
	Node* insertFirst();
	Node* insertFirst(const T& data) { return &(*this->insertFirst() = data); }
private:
	Node *_first;
};
The node class implementation:
template<typename T> typename LinkedList<T>::Node* LinkedList<T>::Node::insertAfter() {
	Node *tmp = new Node;
	tmp->_next = this->_next; // move our next ahead
	this->_next = tmp; // new is our next now
	return this->_next; // return newly inserted node
}

template<typename T> typename LinkedList<T>::Node* LinkedList<T>::Node::removeAfter() {
	if(this->_next) {
		Node *nodebye = this->_next;
		if(this->_next->_next) this->_next = this->_next->_next;
		delete nodebye;
	}
	return this; // return itself
}

template<typename T> typename LinkedList<T>::Node* LinkedList<T>::Node::next(int howMany) {
	Node *ret = this;
	for(int i = 0; i < howMany; ++i) {
		ret = ret->_next;
		if(!ret) break;
	}
	return ret; // howMany=0 returns itself
}

template<typename T> int LinkedList<T>::Node::countAfter() const {
	int ret = NULL;
	Node *no = this->_next;
	while(no) { no = no->_next; ++ret; }
	return ret; // how many nodes exist after us
}
And the linked list implementation:
template<typename T> LinkedList<T>::~LinkedList() {
	Node *node = this->_first;
	while(node) {
		Node *tmpNode = node->next();
		delete node;
		node = tmpNode;
	}
}

template<typename T> typename LinkedList<T>::Node* LinkedList<T>::append() {
	if(!this->_first)
		return ( this->_first = new Node ); // return first and only
	Node *node = this->_first;
	while(node->next()) node = node->next();
	return node->insertAfter(); // return newly inserted node
}

template<typename T> void LinkedList<T>::removeFirst() {
	Node *nodebye = this->_first;
	if(this->_first->next()) this->_first = this->_first->next();
	delete nodebye;
}

template<typename T> typename LinkedList<T>::Node* LinkedList<T>::insertFirst() {
	Node *newly = new Node;
	if(this->_first) newly->_next = this->_first; // only case of FRIEND use
	return this->_first = newly; // return newly inserted node
}
The machinery is pretty straightforward to use, I believe. You just need to declare one instance of the LinkedList class, and all the node manipulation will be done through it and the node pointers returned by the methods, which allows operations on the nodes themselves. You’ll never have to alloc/dealloc any node. Here’s an example, with some operations and then printing all elements:
#include <stdio.h>
int main() {
	LinkedList<int> list;
	list.append(33)->insertAfter(80);
	list.insertFirst(4)->removeAfter();

	LinkedList<int>::Node *node = list[0];
	while(node) {
		printf("%d\n", node->data()); // print each value
		node = node->next();
	}
	return 0;
}

Sunday, May 13, 2012

FLAC and LAME frontend

I use the FLAC and LAME command line tools, and I’ve tried many FLAC and LAME frontends. And I disliked all them. One day I decided to write my own, with a parallel multithreaded handling of the files, so all the files are converted at once, taking advantage of multicore CPUs.

Today I’ve just published it as open source on GitHub. It’s pure C and Win32. I hope it can be useful to someone – not only the program itself, but also my C programming techniques. It can be found at rodrigocfd/flac-lame-gui.

Saturday, May 12, 2012

My first program on GitHub

That’s a simple C Win32 program to shrink down padding bytes from ID3v2 tags on MP3 files. Maybe the most important thing, I think it showcases my style of C programming, and I’m glad to share it with the world. I hope it can be useful to someone someday.

It can be browsed at rodrigocfd/id3-padding-remover.

Wednesday, March 21, 2012

Finding memory leaks in Win32

I’ve just discovered an interesting function to aid the Win32 programmer in finding eventual memory leaks in debugging mode, and with a very straightforward use: _CrtDumpMemoryLeaks.

The function compares the current memory state with the one at the program start, and if any unnalocated memory block is found, it returns TRUE and prints some debug information on the output window. So, to use it effectively, without false positives, one must call it when all objects are out of scope. Here’s an example:
#include <crtdbg.h>
#include <string>
int WINAPI wWinMain(HINSTANCE, HINSTANCE, LPWSTR, int)
{
	std::wstring name = L"abcdef";
	_CrtDumpMemoryLeaks(); // will accuse a leak!
	return 0;
}
In the code above, there will be a false positive, because the string object didn’t go out of scope yet, therefore its destructor wasn’t called so far, so there’s still memory allocated. But this would rather lead to our expectations:
#include <crtdbg.h>
#include <string>
int WINAPI wWinMain(HINSTANCE, HINSTANCE, LPWSTR, int)
{
	{
		std::wstring name = L"abcdef";
	}
	_CrtDumpMemoryLeaks(); // no leaks!
	return 0;
}
Now, since the string was declared within the scope of the nested block, its destructor will be called when the nested block ends, and no memory will remain allocated after it. This way, _CrtDumpMemoryLeaks will correctly report no leaks; indeed, nothing will be printed to the output window.

And the function is removed when _DEBUG is not defined, so you don’t need to worry about it on your release builds.

I particularly found it useful to use the _CrtDumpMemoryLeaks call inside an _ASSERT macro, so that when a memory leak is found, a huge popup will honk right in my face, in addition to the debug messages. So I actually proceed like this:
_ASSERT(!_CrtDumpMemoryLeaks());

Tuesday, March 6, 2012

Load Explorer file extension icon in Win32

When programming with C and Win32, sometimes you need to load an icon, as displayed on Windows Explorer, relative to a file extension. For example, you need to load the Explorer icon associated to the “txt” file extension.

Here is a quick function I use to do it:
HICON ExplorerIcon(const wchar_t *fileExtension)
{
	wchar_t extens[10];
	SHFILEINFO shfi = { 0 };

	lstrcpy(extens, L"*.");
	lstrcat(extens, fileExtension);
	SHGetFileInfo(extens, FILE_ATTRIBUTE_NORMAL, &shfi, sizeof(shfi),
		SHGFI_TYPENAME | SHGFI_USEFILEATTRIBUTES);
	SHGetFileInfo(extens, FILE_ATTRIBUTE_NORMAL, &shfi, sizeof(shfi),
		SHGFI_ICON | SHGFI_SMALLICON | SHGFI_SYSICONINDEX | SHGFI_USEFILEATTRIBUTES);

	return shfi.hIcon; // use DestroyIcon() on this handle
}

// Usage example:
HICON hIconTxt = ExplorerIcon(L"txt");
Remember to release the HICON handle by calling DestroyIcon after using it, or you’ll have a resource leak.

Saturday, February 18, 2012

Hide members on inheritance in C++

I was working on my personal Win32 classes, when I came across something I was willing to do. Suppose I have the following class:
class Base {
protected:
	int someValue;
	void doSomething();
public:
	void thePublicMethod();
	void anotherPublicMethod();
};
Since someValue and doSomething() are protected, they are visible and can be used by any subsequent derived class. Then, let’s have a derived class:
class Derived : public Base {
	void newStuff() {
		someValue = 42;
		doSometing();
	}
};
The public methods are still public. Now see that I used someValue and doSomething() inside newStuff() method, which is private. And now I don’t want subsequent derived classes to have access to someValue and doSometing(). I want to hide them from subsequent derived classes.

At first, I thought it wouldn’t be possible without redefining and overriding, which would add bloat here. But then I came across a trick I didn’t know, which allows you to hide both methods and variables without redefining or overriding them:
class Derived : public Base {
	Base::someValue;
	Base::doSomething; // now they are protected: hidden!

	void newStuff() {
		doSometing();
		someValue = 42;
	}
};
This trick changes the access modifier of methods and member variables without touching them, with zero overhead or additional bloat. Yes, C++ is a damn complex language.

Friday, February 17, 2012

Optimization settings for Visual C++ 2008

These are the optimization settings I use on Visual C++ 2008. These settings are set to the release builds, on the project settings window, and they complement the default release settings.
  • C/C++
    • General
      • Debug Information Format: Disabled
    • Code Generation
      • Enable String Pooling: Yes
      • Enable C++ Exceptions: No
      • Runtime Library: Multi-threaded (/MT)
      • Enable Enhanced Instruction Set: Streaming SIMD Extensions 2 (/arch:SSE2)
  • Linker
    • Debugging
      • Generate Debug Info: No

On debug builds I don’t change the settings much: I just disable the C++ exceptions, and enable the SSE2 and the string pooling.

Wednesday, September 21, 2011

A sprintf with automatic memory allocation

Personally, I’m a sprintf lover. Not only in C, but in any program language that implements it. I use sprintf all the time, it’s extremely simple, clean and quick.

The sprintf version found on the C standard library requires a previously allocated memory space, where the formatted string will be placed after the operation. However, there are many times where you don’t know how long the result string can be, or you simply don’t want to waste space with a “worst case scenario” allocation. I used to face this a lot. There’s a GNU extension called asprintf, which you can use on Linux, but it doesn’t return the pointer, it returns the number of bytes – although it’s fine, it’s not exactly what I wanted.

So I decided to write my own version of a sprintf function which automatically finds out how much space is needed, allocates the memory and then returns the pointer, with the formatted string. Then I just have to free the pointer after use.

In order to accomplish this task, I used some least known functionalities from the C standard library, so it may be interesting to you to study how I did the job, so the technique can be applied when you need. Also, I found out that some of them behave differently on Linux and Win32. The idea is simple, though: find out how much memory is needed; allocate the memory; call sprintf; return the pointer. After all, I ended up with a valuable and handly function to work with.

This is the Linux version:
char* allocfmt(const char *fmt, ...)
{
	va_list ap;
	va_start(ap, fmt);
	int len = vsnprintf(0, 0, fmt, ap);
	va_end(ap);

	va_start(ap, fmt);
	char *retbuf = malloc(sizeof(char) * (len + 1));
	vsprintf(retbuf, fmt, ap);
	va_end(ap);
	return retbuf;
}
And this is the Unicode-ready Win32 version:
#include <tchar.h>
#include <windows.h>
LPTSTR allocfmt(LPCTSTR fmt, ...)
{
	va_list ap;
	va_start(ap, fmt);
	int len = _vsctprintf(fmt, ap);
	TCHAR *retbuf = malloc(sizeof(TCHAR) * (len + 1));
	_vsntprintf(retbuf, len, fmt, ap);
	va_end(ap);

	*(retbuf + len) = 0;
	return retbuf;
}

Wednesday, September 14, 2011

Fast, in-place C string trim

I want to share with the world this code for a fast trim function in C which is part of my personal library, and that I use quite often. It performs both left and right trim as an in-place operation, changing the original string. The return value is the same pointer that was passed as argument.

This is the version I use on Linux:
char* trim(char *s)
{
	char *pRun = s;
	while(*pRun == ' ') ++pRun;
	if(pRun != s)
	memmove(s, pRun, (strlen(pRun) + 1) * sizeof(char));
	pRun = s + strlen(s) - 1;
	while(*pRun == ' ') --pRun;
	*(++pRun) = 0;
	return s;
}
And this is the version I use on Win32, which is Unicode-ready:
LPTSTR trim(LPTSTR s)
{
	TCHAR *pRun = s;
	while(*pRun == TEXT(' ')) ++pRun;
	if(pRun != s)
	memmove(s, pRun, (lstrlen(pRun) + 1) * sizeof(TCHAR));
	pRun = s + lstrlen(s) - 1;
	while(*pRun == TEXT(' ')) --pRun;
	*(++pRun) = 0;
	return s;
}

Wednesday, July 20, 2011

Dialog based Win32 programs

This is the kind of program I write most: C/C++, pure Win32 API, dialog box based. Over the years I developed a couple of handful routines that I believe to be pretty solid nowadays, since I use them without any modification for some years already, and they work flawlessly.

I decided to share this knowledge with everyone mainly because today I see a lot of .NET programs – or even worse, WPF – that most of the time they could have been written in good Win32, avoiding the huge amounts of bloating you have to carry with those “modern” libraries. I know C/C++ is not for everyone, pointers demand care, but I strongly believe that any respectable programmer should have a clear understanding of the C language. Otherwise, he’s just a script kiddie.

Modern languages with garbage collectors overprotect the programmers, much like those overprotective parents do with their children – and we all know these children become problematic, limited adults.

So stop being lazy and go learn C. And after you learn C, you can read my article on Win32 programming, that I published on CodeProject today.

Saturday, July 9, 2011

Replay Gain

I’d say this Replay Gain thing is the coolest thing that appeared on the personal computer music listening world since the birth of Winamp in 1997.

How it works: first you use a Replay Gain scanner to add a couple new tags to each song of your music library. These new tags stamp a relative perceived loudness level corrector to each song, so that when your player plays them, it will raise or lower the volume accordingly, and all the songs will have the same volume (or almost), and you don’t need to raise/lower the volume yourself anymore. This is specially useful if you have a long playlist in shuffle mode, with songs at all sorts of different volumes.

Several music players of today implement Replay Gain, but some of them don’t perform the scan. If you want a suggestion, try foobar2000, it can do all the job.

Corollary: if you have a large and heterogeneous music library, Replay Gain will make you smile.

Now on the technical side: I found what it seems to be the C implementation of the Replay Gain scanner at the (rather old-school) project site. It really drove me curious, I guess I’ll download and try to compile it later.