Category Archives: Windows

C++ Code and Assembly traduction in Release

Do you know why C++ is the best ? Because it can be high level and very focus on optimized asm code generation. Here a sample of code:

 

#include "pch.h"

class Param
{
};

template<typename T>
class Factory
{
public:
static shared_ptr<T> CreateObject(const Param& param)
{
shared_ptr<T> pObj = nullptr;
pObj = make_shared<T>();

_pLastElement = pObj;
return pObj;
}

static shared_ptr<T> GetLastCreatedObject()
{
return _pLastElement;
}

private:
static shared_ptr<T> _pLastElement;
};

template<typename T>
shared_ptr<T> Factory<T>::_pLastElement = nullptr;

class Employee
{
};

class Product
{
};


template<typename T>
class Vector
{
public:
Vector(int size)
{
_size = size;
_data = new T[_size];
}

~Vector()
{
delete[] _data;
}

T GetData(int index)
{
return _data[index];
}

void SetData(int index, T value)
{
_data[index] = value;
}

private:
T* _data;
int _size = 0;
};

int main()
{
Vector<int> v1(10);
v1.SetData(2, 20);
int value = v1.GetData(2);
cout << value << endl; //20

Vector<string> v2(1000);
v2.SetData(10, "string 10");
v2.SetData(100, "string 100");
string value2 = v2.GetData(10);
cout << value2 << endl; // string 10

Vector<Product> v3(200000);

Param param;
shared_ptr<Employee> p1 = Factory<Employee>::CreateObject(param);
if (p1 != nullptr)
{
cout << "OK" << endl; //OK
}
shared_ptr<Employee> p2 = Factory<Employee>::CreateObject(param);
shared_ptr<Employee> p3 = Factory<Employee>::CreateObject(param);

shared_ptr<Employee> pLast = Factory<Employee>::GetLastCreatedObject();
if (pLast == p3)
{
cout << "OK ptr" << endl;
}
}

The result is an associated asm code generated : here

There is approximatively 1000 lines of asm for 100 lines of C++ with templates and shared_ptr. It’s amazing !

C++ rocks.

How to become a Windows Expert ?

This article is the continuation of How to become a Microsoft Expert? (http://netazurerangers.com/blog/comment-devenir-un-expert-microsoft/)

Windows has been Microsoft’s technological flagship for 25 years. You will tell me, yes but now there is Azure. OK but what is Azure? It is ; if I ignore the Linux part; Windows Server and Service Fabric… and that’s Windows. It’s C / C ++. And yes, again! There is no secret. it must work quickly and well. It must be reliable, robust, fast and secure.

In one of my last post “C ++ unsafe and unsecure?” (http://netazurerangers.com/blog/c-unsafe-et-unsecure/), I explain why C / C ++ is the best and why Microsoft is doing 95% of its products with. Microsoft is the # 1 company in the software industry. It’s not an advertising agency like Google or Facebook, it’s pure juice Tech. Microsoft sells Products and Services. Anyway next…

How to become a Windows expert? The question is asked. First, we learn about the operating system principles via Microsoft Docs (ex: MSDN LIbrary) on https://docs.microsoft.com/en-us/windows-hardware/drivers/kernel/overview-of-windows -components

Then, we read the passage on User mode and Kernel mode via https://docs.microsoft.com/en-us/windows-hardware/drivers/gettingstarted/user-mode-and-kernel-mode

From there, we know the basic architecture of Windows. now we attack the elements on the operating system, namely the kernel and the thread scheduler. Windows order threads, Linux order processes. These two systems do not work the same way. The Processes & Threads doc is here: https://docs.microsoft.com/en-us/windows/win32/procthread/about-processes-and-threads

Then we go to practice, how to create a thread, a process, reach the end, etc. the API doc also called reference doc is here: https://docs.microsoft.com/en-us/windows/win32/procthread/process-and-thread-reference

The easiest examples can be viewed via https://docs.microsoft.com/en-us/windows/win32/procthread/process-and-thread-functions#process-and-thread-functions and more specifically the CreateThread function: https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createthread?redirectedfrom=MSDN and its example: https://docs.microsoft.com/en-us/windows / win32 / procthread / Creating-threads

To test this, you must install Visual C ++ available in Visual Studio 2019 for example, Community Edition or Pro 30 day trial. If you received money from Santa Claus, buy the following books:

Windows via C / C ++ by Jeffrey Richter and Christophe Nasarre

Windows Internals ex-Inside Windows NT (https://docs.microsoft.com/en-us/sysinternals/learn/windows-internals)

I bought Inside Windows NT in 1992 and got the virus.

Windows is huge. It’s powerful. You read the Windows Internals book and you will have vision; you will understand how the OS works. It’s very interesting and you will have no trouble understanding new Microsoft technologies with that. Microsoft NET, CLR, BCL, it’s done with C ++ and parts of the Windows API aka Win32. Watch the code on GitHub of CoreCLR (https://github.com/dotnet/runtime)

There are urban legends that Microsoft rewrites Windows from scratch; this is for managers and IT 01. For technicians, the truth is that Windows is sitting on the same code and has been evolving for 25 years. The code is improved and regularly revised in Modern C ++. I can certify it because I have the source code of Windows NT 4, Windows 2000 and access to the latest source code of Windows 190x. The code is made in:

C for kernel and drivers
in C / C ++ for the rest.
What is Modern C ++?

automatic memory release with smart points
using the Standard Template Library (STL)
use of C ++ 11/14/17 with auto, lambdas, etc.
Windows uses COM technology a lot. A COM component is registered in the registry and is invoked via APIs (https://docs.microsoft.com/en-us/windows/win32/api/_com/)

A COM component is a class with AddRef, Release, QueryInterface and methods:

The COM component is created via CoCreateObject and the COM factory:

For more information on COM components, I made in 200x a translation of some elements of “Inside COM + Base Services”: Apartments | Threads | Apartments types | Threading for In-Proc components | Apartment and languages

For more information on COM, get your hands on Inside COM + Base Services (http://www.windowscpp.com/Books/MSPress-InsideCOMBaseServices.zip) or on docs but on docs, the doc is spartan.

201x saw Microsoft turn to open source so you can find Windows components in open source:

Windows Terminal (https://github.com/microsoft/terminal)
Windows NET CoreCLR (https://github.com/dotnet/runtime)
Do like me, study these two modules and try to contribute in GitHub. And who knows, one day, you may work for Microsoft!

Chick!

Christophe | http://www.christophepichaud.com

Multiplatform development with C++

To develop multi-platform applications, there are not fifty possible choices, there is only one that is free and efficient: it’s C++.

Only the C/C++ can take advantage of the latest developments in Windows, Linux, Android and iOS SDKs because the system and its environment are made with it. The advantage of C++ is that it ‘builds on the metal’: there is no faster. It takes advantage of the software architecture of the operating and hardware systems of the latest x86, x64 and ARM processors. For forty years, C++code optimizers have guaranteed the best possible quality of code.

C, It’s the new assembler. C++, It allows the object oriented: abstractions, inheritance and polymorphism (virtual functions), overload of operators, templates. With its STL (Standard Template Library) bookstore and in conjunction with a bookstore such as Boost (boost.org), the C++ a-has a universal toolbox that handles strings, containers (collections), algorithms, I/O, threads, smart pointers, communications, etc.

Take the plunge. Install Visual C++ Windows, GCC Linux, XCode on Mac and share business code. Make rich graphical interfaces and take advantage of the best development language that’s C++.

You will tell me there are hybrid solutions like NET or Java? These solutions are a set of thousands of heavy, slow sheets that do not create world-class applications. In cars, there are Fiat 500s and Ferraris. At the same price (see cheaper), what do you take? There’s no photo…

Article for Programmez October 2019

In the N°233 Issue of Programmez magazine, I have written a technical article about Windows Subsystem for LInux v2 (WSL2).

Article for Programmez – November 2018 – Windows Multithreading in C/C++

This article will be available next month.

Programmez_223

Article for Programmez – September 2018 – Writing a NoSQL Windows Web Service with C++

This article is available now in kiosks for Programmez.

Programmez221

DevCon6 conference by Programmez Magazine

On stage yesterday for DevCon6 Conference ; a live coding show in Paris organized by Programmez Magazine. My session was about the C language of Daddy ! And the implementation of LMDB NoSQL under Windows. It’s fast ! 1.000.000 rows inserted in 2 seconds !

Need a simple logger in Win32 ?

If you need like me, a logger for your deamons and services… just look at this simple logger:

#pragma once
#include <string>

class CLogger
{
public:
	CLogger();
	virtual ~CLogger();

public:
	void Init(std::wstring name);
	void WriteLog(std::wstring message);

private:
	std::wstring _name;
	std::wstring _path;
};

You put the name of the file in Init() method as then, you just call WriteLog() ! Let’s ook at the code impl:

#include "stdafx.h"
#include "Logger.h"


CLogger::CLogger()
{
}


CLogger::~CLogger()
{
}

void CLogger::Init(std::wstring name)
{
	_name = name;

	TCHAR szTemp[255];
	_stprintf_s(szTemp, _T("C:\\TEMP\\LOGS"));
	::CreateDirectory(szTemp, NULL);

	TCHAR szPath[255];
	_stprintf_s(szPath, _T("%s\\%s"), szTemp, name.c_str());

	_path = szPath;
}

void CLogger::WriteLog(std::wstring message)
{
	std::string path(_path.begin(), _path.end());

	SYSTEMTIME st;
	memset(&st, 0, sizeof(SYSTEMTIME));
	::GetSystemTime(&st);

	TCHAR sz[1024];
	_stprintf_s(sz, 
		_T("%02d:%02d:%02d.%03d - INFO - %s\r\n"), 
		st.wHour, st.wMinute, st.wSecond, st.wMilliseconds, 
		message.c_str());

	std::wstring wsz = sz;
	std::string msgToWrite(wsz.begin(), wsz.end());

	HANDLE hFile = ::CreateFileA(path.c_str(), 
		GENERIC_WRITE, FILE_SHARE_WRITE, 
		NULL, OPEN_ALWAYS, 
		FILE_ATTRIBUTE_NORMAL, NULL);

	LONG l = 0;
	::SetFilePointer(hFile, 0, &l, FILE_END);
	
	DWORD dwLen = 0;
	::WriteFile(hFile, 
		msgToWrite.c_str(), msgToWrite.length(), 
		&dwLen, NULL);
	
	::CloseHandle(hFile);

	printf_s(msgToWrite.c_str());
}