Archives

Date

Visual C++ Debugging: How do I evaluate the time difference between two events?

Q: How do I evaluate the time difference between two events?
A: Accurate time difference between events cannot be evaluated by clocking the time using 'CTime::GetCurrentTime()' or by using a timer. First method is limited in its accuracy to around a second and second method has limitations of lower priority.

Here I present a function which returns the time elapsed from the last call. First call will always return a zero value. This uses the high-resolution performance counter. If it does not exist, each call will return zero.

float TimeDiff()
{
// Last counter reading
static LARGE_INTEGER OldCounter = {0, 0};
LARGE_INTEGER Counter, Frequency;
if
(QueryPerformanceFrequency(&Frequency))
{
// Gets current counter reading
QueryPerformanceCounter(&Counter);
// Calculates time difference (zero if called first time)
float TimeDiff = OldCounter.LowPart ? (float) (Counter.LowPart - OldCounterLowPart) / Frequency.LowPart : 0;
// Resets last counter reading
OldCounter = Counter;
// Returns time difference
return TimeDiff;
}
else
{
// No high resolution performance counter; returns zero
return 0;
}
}

Time difference is returned in seconds and the accuracy is determined by the high-resolution performance counter frequency.
Note: Most of the material in this article is taken from codeguru.com


Recommended Reading :

Visual C++ Network: How to get the local IP address(es)?

Q: How to get the local IP address(es)?
A: The following example will get up to ten assigned IP addresses...

#include <winsock2.h>
// Add 'ws2_32.lib' to your linker options
WSADATA WSAData;
// Initialize winsock dll
if(::WSAStartup(MAKEWORD(1, 0), &WSAData))
// Error handling
// Get local host name
char szHostName[128] = "";
if
(::gethostname(szHostName, sizeof(szHostName)))
// Error handling -> call 'WSAGetLastError()'
// Get local IP addresses
struct sockaddr_in SocketAddress;
struct
hostent *pHost = 0;
pHost = ::gethostbyname(szHostName);
if
(!pHost)
// Error handling -> call 'WSAGetLastError()'
char aszIPAddresses[10][16]; // maximum of ten IP addresses
for(int iCnt = 0; ((pHost->h_addr_list[iCnt]) && (iCnt < 10)); ++iCnt)
{
memcpy(&SocketAddress.sin_addr, pHost->h_addr_list[iCnt], pHost->h_length)
;
strcpy(aszIPAddresses[iCnt], inet_ntoa(SocketAddress.sin_addr));
}
// Cleanup
WSACleanup();

As with everything, there exists of course other ways and other information which can be retrieved...some examples can be found in the following knowledge base article.

Note: Most of the material in this article is taken from codeguru.com


Recommended Reading :

Visual C++ Network: How to get the local hostname?

Q: How to get the local hostname?

A:

#include <winsock2.h>

// Add ws2_32.lib to your linker options

WSADATA WSAData;

// Initialize winsock dll
if(::WSAStartup(MAKEWORD(1, 0), &WSAData) == FALSE)
// Error handling

// Get local host name
char szHostName[128] = "";

if
(::gethostname(szHostName, sizeof(szHostName) - 1))
// Error -> call 'WSAGetLastError()'

// Cleanup
WSACleanup();
Note: Most of the material in this article is taken from codeguru.com
Recommended Reading :

Visual C++ DLL: How to build a DLL to be used from another programming language?

Q: How to build a DLL to be used from another programming language?

A: When you create a DLL with Visual C++, and you want to use the DLL with other languages, there are a few things that you should do (creating a DLL isn't just compiling code).

  1. Make sure your exported functions are declared as extern "C". The reason for this is so that the C++ name mangling is not used on the exported function names.
  2. Make sure your exported functions use '__stdcall' calling convention. The reason for this is that most other Window's languages assume the exported functions retrieve parameters starting from the rightmost parameter, and that the function called is responsible for stack cleanup on return. By default C and C++ functions assume '__cdecl' calling convention.
    You won't know when this problem exists until you call the exported function in your Delphi program. You did not declare
    your function as '__stdcall', so your [insert porgramming language, other than C/C++, here] program would have crashed as soon as you called the function.
  3. Use '__declspec(dllexport)'. This is so that the function can be exported (of course).
  4. Use a module definition file (.def-file). This removes the "@x" decoration that appears at the end of VC++ exported function names, where "x" is the total number of bytes in the arguments passed to the function. When the user of the DLL is using another language, the programmer would rather call "tempest", not "tempest@4". Yes, many of these other languages have an "aliasing" features so that you can access the function by a different name, but it is a pain in the neck. Just use a .def-file to remove the additional decoration and you won't have to do anything else.

Note: Just exporting the name does *not* remove all the decoration - you must follow steps a) *and* d). A lot think that you only need to do a) and b) and c). This is if you plan on using the DLL in only Visual C++. If you leave the module definition file out of these steps, you will get what you're seeing now -- an exported name that is not what you expect.

If you do a search on CodeGuru, your question has been asked many times in various ways, and the reason for the problem is almost always that step d) was left out.
Here is a sample of a module-definition fie (DEF file).
LIBRARY YOURDLL
DESCRIPTION 'This is my DLL
EXPORTS
Whatever1 @2
Whatever2 @3

The LIBRARY command must match the name of your DLL. So if your DLL is named YOURDLL.DLL, the LIBRARY command is followed by YOURDLL.

The DESCRIPTION is any description you feel is appropriate for your DLL. The actual description is preceeded by a single quote (').

The EXPORTS lists the functions that you exported, along with an ordinal number. It doesn't matter what ordinal numbers you use, so long as you maintain different numbers for each function, and you shouldn't change the ordinal numbers when you create an upgraded version of your DLL -- persons preferring to use ordinal numbers to call your functions will get angry.
Note: Most of the material in this article is taken from codeguru.com

 


Recommended Reading :

Visual C++ General: How to use different character sets?

Q: I have this simple function call:

MessageBox(NULL, "Test message", "Title", MB_OK);


The compiler raises the following error and I don't understand why.

error C2664: 'MessageBoxW' : cannot convert parameter 2 from 'const char [13]' to 'LPCWSTR'
Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast

A: Simply answered, that happens because the project is built for UNICODE.

Microsoft run-time library provides Microsoft-specific generic-text mappings for many data types, routines and other objects, mappings that are defined in TCHAR.h. There are three supported character sets:[/list][*]ASCII (single-byte character set

C++ STL : What is the meaning of the 'Alloc' template parameter in 'vector'?

Q: What is the meaning of the 'Alloc' template parameter in 'vector'?
Q: How do I define my own allocator for use in STL containers?


A: The whole concept is very well explained in Gabriel and Andreas' article about Allocators.

The template parameter 'Alloc' specifies the type of allocator that the container should use to manage its memory. Every time the container needs a bit of memory, it will ask the allocator to retrieve it for him. The allocator usually just calls 'new' (and 'delete' when it has to free memory), but there can be more sophisticated strategies for allocators.

Usually, you are fine with the standard allocator provided by your STL. However, at times you may need to specify the allocation strategy explicitly. In theory, writing a custom allocator is not very difficult, but the task is complicated by the fact that the standard C++ design relies on template member functions which quite a few compilers don't support (e.g. Visual C++ 6).

A simple example for an allocator which never frees memory is this code (note that you need a recent compiler to get this to work):

#include <limits>
const size_t TEST_SIZE = 10000;
const double
TIME_MULTIPLIER = 100.0;
const
size_t MAX_SIZE = (TEST_SIZE + 1) * 12;
class
MemoryPool
{
unsigned char *m_data;
size_t m_top;
int
m_refcount;
public
:
MemoryPool()
{
m_data
= new unsigned char[MAX_SIZE];
m_top = 0;
m_refcount = 0;
}
~MemoryPool()
{
delete [] m_data;
}
void AddRef()
{
++m_refcount
;
}
void *alloc_mem(size_t n)
{
if ((MAX_SIZE - m_top) >= n) {
size_t old_top
= m_top;
m_top += n;
return
m_data + old_top;
} else {
return 0;
}
}
void Release()
{
if (--m_refcount == 0) {
delete this;
}
}
}
;
template
<class T>
class MyAlloc {
public:
// type definitions
typedef T value_type;
typedef
T* pointer;
typedef const
T* const_pointer;
typedef
T& reference;
typedef const
T& const_reference;
typedef
std::size_t size_type;
typedef
std::ptrdiff_t difference_type;
// rebind allocator to type U
template <class U >
struct rebind {
typedef MyAlloc< U > other;
};
// return address of values
pointer address (reference value) const {
return &value;
}
const_pointer address (const_reference
value) const {
return &value;
}
/* constructors and destructor
* - nothing to do because the allocator has no state
*/
MyAlloc() throw() {
m_pPool
= new MemoryPool;
m_pPool->AddRef();
}
MyAlloc(
const MyAlloc& src) throw() {
m_pPool
= src.m_pPool;
m_pPool->AddRef();
}
template <class U >
MyAlloc (
const MyAlloc< U > &src) throw() {
m_pPool
= src.m_pPool;
m_pPool->AddRef();
}
~MyAlloc()
throw() {
m_pPool->Release()
;
}
// return maximum number of elements that can be allocated
size_type max_size () const throw() {
return MAX_SIZE / sizeof(T);
}
// allocate but don't initialize num elements of type T
pointer allocate (size_type num, const void* = 0) {
// print message and allocate memory with global new
pointer ret = (pointer) m_pPool->alloc_mem(num * sizeof(T));
return
ret;
}
// initialize elements of allocated storage p with value value
void construct (pointer p, const T& value) {
// initialize memory with placement new
new((void*)p)T(value);
}
// destroy elements of initialized storage p
void destroy (pointer p) {
// destroy objects by calling their destructor
p->~T();
}
// deallocate storage p of deleted elements
void deallocate (pointer p, size_type num) {
// do not deallocate memory
}
MemoryPool *m_pPool
;
};
// return that all specializations of this allocator are interchangeable
template <class T1, class T2>
bool operator== (const MyAlloc<T1>&, const MyAlloc<T2>&) throw() {
return true;
}
template <class T1, class T2>
bool operator!= (const MyAlloc<T1>&, const MyAlloc<T2>&) throw() {
return false;
}

Note
: Most of the material in this article is taken from codeguru.com
Recommended Reading :

C++ STL : How to remove elements of a particular value from a container ?

Q: What is the best way to remove all elements of a particular value from a container?
A: Use the so-called 'remove/erase' idiom:

// taken from Item 32 of Scott Myers' Effective STL
vector<int> v;
v.erase(remove(v.begin(), v.end(), 99), v.end());

This is because of the simple fact that 'remove()' is a generic algorithm which takes iterators as its arguments. The iterators know nothing of their container; the STL was designed so as to grant the smallest possible amount of coupling. Thus, the iterators cannot call any container's 'erase()' or similar function.

'remove()' DOES return the container's new 'end()' (which just
happens to be the first element that was removed) and this value
can be used in the container's 'erase()' call.

Note: Most of the material in this article is taken from codeguru.com


Recommended Reading :

C++ : How to convert from std::string to CString?

Q: How to convert from std::string to CString?

A: This is simple... Use the CString constructor.

std::string strStdString ("Hello!");
// Using CString Constructor
CString strCString (strStdString.c_str ());

Let me add that CStringT can construct from both character or wide-character strings. i.e. It can convert from char* (i.e. LPSTR) or from wchar_t* (LPWSTR).

In other words, char-specialization (of CStringT) i.e. CStringA, wchar_t-specilization CStringW, and TCHAR-specialization CString can be constructed from either char or wide-character, null terminated (null-termination is very important here) string sources.

Q: How to convert from CString to std::string?

A: There are really many ways to do it.

But, the simplest one is just this -

CString strSomeCstring ("This is a CString Object");
// Use ANSI variant CStringA to convert to char*; construct from it -
std::string strStdString (CStringA (strSomeCstring));

CStringA is a template specialization of class CStringT for type char avaílable with Visual Studio 7.x and better.

Q: What are correlations between the CString Family and the Standard String Family?

A: If we were to draw a correlation between the CString Family and Standard String Classes, we would notice -

  1. CStringT as the equivalent of std::basic_string
  2. CStringA as the equivalent of std::string
  3. CStringW as the equivalent of std::wstring

However, the standard library itself doesn't contain a "CString" equivalent - one that can at best be -

std::basic_string <TCHAR>

This makes CString (VS 7.x +) "cool".

Q: The history of CString...

A: CString really wasn't always as likeable as it is today. If one were to compare the CString of Visual Studio 7.x and better with the class supplied by MSVC 6.0, one might not be wrong in judging the erstwhile version as relatively inflexible, and restrictive.

What made CString of yesterday "inflexible"?

1.Only for MFC-folks!

Yes... CString with MSVC 6.0 was notoriously connected to MFC Projects as if other project types didn't have any need for a TCHAR String Wrapper Class! One reason for it would be the linker error one would get for using this class in a non-MFC Project.

2. Need to use a CString? Convert to TCHAR!

CString is a string wrapper for TCHAR strings. In doing so, it came with a good number of helpful member methods. However, the implementation of this class in MSVC 6.0 was such that if a programmer needed to make use of the utility member methods, he would need to convert his string data type to TCHAR - back and forth.

This "restriction" automatically excluded programmers using ANSI strings (char*) in UNICODE builds from using this class, and ditto for those using UNICODE strings (WCHAR*) in non-UNICODE builds from using this class - as in both these cases, the strings in question aren't TCHAR strings - the type that CString wraps.

What makes CString of today "flexible" and actually more "likeable"?

1. Use it in any project type - even in a console application!

Yes... All the programmer needs to do is to include the following header -

#include <atlstr.h>

 

2. Don't change your String Type to suit CString! Choose the right CString instead!

With Visual Studio 7.x and better, CString is actually a specialization of template Class CStringT for type T as TCHAR.
Additionally, there exist two useful specializations of CStringT -

  • CStringA that specializes CStringT for type char, and
  • CStringW that specilizes CStringT for type wchar_t.
Hence, CString is actually CStringA for a non-UNICODE build and is a CStringW for a UNICODE build.

The existence of CStringA and CStringW gives the programmer, the flexibility to use the utility member methods supplied by CStringT even when their strings aren't of type - TCHAR.

Note: Most of the material in this article is taken from codeguru.com


Recommended Reading :

C++ String: What is the difference between '\n' and '\r\n'?

Q: What is the difference between '\n' and '\r\n'?

A:
Background
There are a few characters which can indicate a new line. The usual ones are these two:

  • '\n' or '0x0A' (10 in decimal) -> This character is called "Line Feed" (LF).
  • '\r' or '0x0D' (13 in decimal) -> This one is called "Carriage return" (CR).

Different Operating Systems handle newlines in a different way. Here is a short list of the most common ones:
  • DOS and Windows

    They expect a newline to be the combination of two characters, namely '\r\n' (or 13 followed by 10).

  • Unix (and hence Linux as well)

    Unix uses a single '\n' to indicate a new line.

  • Mac

    Macs use a single '\r'.

This difference gives rise to a number of problems. For example, a file created under Unix (so with newlines as a single LF) will not open correctly under Window's Notepad. Any Windows program that expects newlines to be CRLF will not work correctly with these files.

To unify things a bit, so that writing portable C/C++ programs is possible, file streams have both a "translated" and an "untranslated" mode. If you open a file in translated mode, the runtime library will convert a '\n' to the appropriate newline character(s). If the following program is compiled under Unix, the file will contain a single LF to indicate the newline. If it's compiled under windows, it will contain a CRLF.

#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp = fopen("testfile.txt", "w");
fprintf(fp, "Hello World\n");
fclose(fp);
return 0;
}

If you look at the generated file with a hex editor, you will see that the windows version has generated the following:

H e l l o W o r l d CR LF

0x48 0x65 0x6C 0x6C 0x6F 0x20 0x57 0x6F 0x72 0x6C 0x64 0x0D 0x0A

So file streams are handled in a transparent way, provided of course that you only handle files compatible with your operating system. But many times you have to pass multi-line strings directly to some system functions.

In practice
In Windows you have to pass multi-line strings with '\r\n', otherwise the system functions don't recognize them correctly as multi-line. This is true e.g. for setting the text of Edit controls, Labels, Windows etc. Also, when you read multi-line text from a file that initially contains '\r\n' in translated mode, the string in memory will contain only a single '\n'. See for example the documentation on MSDN about 'fread()':

Originally Posted by MSDN
The fread function reads up to count items of size bytes from the input stream and stores them in buffer. The file pointer associated with stream (if there is one) is increased by the number of bytes actually read. If the given stream is opened in text mode, carriage return

C++ String: What types of strings are there?

Q: What types of strings are there?

A:

  • 'char*' -> this is also called a C-style string, or an ANSI string.

  • 'wchar_t*' -> this is wide character string, i.e. an 'unsigned short*'

  • 'CString' -> this is a string wrapper class, which is part of the Microsoft Foundation Classes (MFC).

  • 'std::string' -> this is a Standard C++ Class wrapping a char string. It is part of the Standard Template Library, or STL.

  • 'std::wstring' -> this is a Standard C++ Class wrapping a wchar_t string. It is part of the Standard Template Library, or STL.

  • 'BSTR' -> this known as basic string or binary string, and is a pointer to a wide character string used by Automation data manipulation functions.

Note: Most of the material in this article is taken from codeguru.com


Recommended Reading :




Internet Marketing - Phoenix Landscaping - Phoenix Pools - Credit Cards