Wednesday, December 7, 2016

How to "interface" Runtime Error Handling between C++11 (Modern C++) and C Code

This post explore the idea to interface runtime error handling between C++11 and C. This is important because most OS API are exposed via C libraries. Moreover, there are countless C libraries out there that uses C-styled runtime error handling as well.

Anyway, before moving further I want to emphasize that assertion has a different goal compared to runtime error handling. Assertion is meant to be used to catch logic error in your code during development, before the program/executable is released/used in operational environment. Therefore, this post doesn't concern the use of assertion. This post will focus on runtime errors caused by "invalid" state of system resources, such as non-existing file, failure to allocate heap memory, etc. Preliminary information on when to use assertion can be found over at MSDN: Errors and Exception Handling (Modern C++). The MSDN article is rather centered on Microsoft-platform. But, the principles explained in it are applicable to any C/C++ code.

Lets get back to the main theme: runtime error handling interface between C++11 and C code. MSDN provided a sample solution to the problem as well: How to: Interface Between Exceptional and Non-Exceptional Code. Unfortunately, the sample provided by MSDN still doesn't use C++11 smart pointer to manage the file HANDLE resource that it uses. Moreover, it's Windows-centric. Therefore, it's not a "pure" C++11 solution yet. However, the idea presented by the MSDN sample is profound and has been adopted in the code for my previous post about using custom deleter.

The basic idea for runtime error handling in C and C++ is different:
  • In C, you have the errno variable from the standard C library or if your code runs in Windows you can query the error code via GetLastError(). Because I'm trying to be platform independent, let's focus on using errno. In C, your code checks the value of the errno variable after a call to a C library function to check for runtime error. Side note: This C runtime error approach is akin to "side-band" signaling in hardware protocol because you don't get the full picture from the return value of the called function. Instead, you need to check other variable via different means. 
  • In C++, your code should be using exception as the mechanism to propagate error "up-the-stack" until there is a "handler" that can handle the error. If the error is unhandled, the standard behavior is to call std::terminate which normally terminate the application.
Looking at the two different mechanisms for runtime error handling in both C and C++, you must have come up with the answer: wrap the C error code into C++ exception.  I provide a sample code that shows how to wrap C error code into C++ exception at https://bitbucket.org/pinczakko/custom-c-11-deleter--it's an updated version of my C++11 custom deleter sample code. Feel free to clone it. The rest of this post explains the code in that Bitbucket URL.

The steps to wrap C error code into C++11 exception are:
  1. Create an exception class that derives from runtime_error class.
  2. Store the error code/number in that exception class.
  3. Create a method in that exception class that transforms the error code into human readable error message (string).
  4. Throw an object of the exception class type in places where a runtime error might occur.
  5. Catch the exception in the right place in your code. 
The preceding steps are not difficult. Lets examine the sample code in more detail to understand the steps.

The exception class is FileHandlerException. It's defined as follows:
class FileHandlerException : public runtime_error
{
public:
    explicit FileHandlerException(int errNo, const string& msg):
        runtime_error(FormatErrorMessage(errNo, msg)), mErrorNumber(errNo) {}

    int GetErrorNo() const {
        return mErrorNumber;
    }

private:
    int mErrorNumber;
};
The FileHandlerException class is derived from runtime_error class--the latter is part of stdlibc++ in C++11. The FileHandlerException class uses its mErrorNumber member to store the error code (errno value) obtained from C. The FormaErrorMessage() function is a custom function that transforms errno value into human-readable string via the C strerror() function. This is FormaErrorMessage() function implementation:
string FormatErrorMessage(int errNo, const string& msg)
{
    static const int BUF_LEN = 1024;
    vector<char> buf(BUF_LEN);
    strncpy(buf.data(), strerror(errNo), BUF_LEN - 1);

    return string(buf.data()) + "   (" + msg + ")   ";
}
As you see, it's not difficult to implement the wrapper for C runtime error code. Lets proceed to see how the exception class is being used.
explicit FileHandler (const char* path, const char* mode)
try:
        mPath{path}, mMode {mode}
    {
        cout << "FileHandler constructor" << endl;

        FILE* f = fopen(path, mode);

        if (f != NULL) {
            unique_ptr<FILE, int (*)(FILE*)> file{f, closeFile};
            mFile = std::move(file);

        } else {
            throw FileHandlerException(errno, "Failed to open " + string(path));
        }

    } catch (FileHandlerException& e) {

        throw e;
    }
In the preceding code, if the call to fopen() failed to produce a usable FILE object, an exception object of type FileHandlerException is initialized and thrown. The catch part of the code simply re-throw the exception object higher-up the stack. The code that finally catches the exception object is shown below.
try {
        DeleterTest::FileHandler f(argv[1], "r");
        //.. irrelevant code omitted
    } catch (DeleterTest::FileHandlerException& e) {

        cout << "Error!!!" << endl;
        cout << e.what() << endl;
        cout << "errno: " << e.GetErrorNo() << endl;
    }
The final "handler" of the exception object simple shows the error string associated with the runtime error, i.e. what causes the failure to obtain a valid FILE pointer.

One final note about exception support in C++11: There is no comprehensive support for Unicode character set yet. I've looked up the web for explanation on the matter but all of them have the same conclusion. Please comment below if you know better answer or update to the problem.

Hopefully, this post is useful for those doing mixed C and C++ code development.

Friday, November 25, 2016

Dealing with Opaque C Pointer in C++11

This post explains how to deal with opaque C pointer in C++11--read: how to interface with C in C++11.  This is important to know for those working on real world C++11 code because there are many C libraries out there that uses opaque pointer as their "interface" to other code, which in this particular case: C++11 application. It's also important to know for C++11 programmers because the way C++11 implement an opaque "interface" is different.

Now, let's detour a bit to "native" C++11 interface. The "native" C++11 interface is known as Compilation Firewalls, an opaque C++ interface "on steroid". These are the relevant articles on it:

Just read both of the links to learn more about C++11-style "native" interface. I'm not going to talk about it here.

Let's get back to our problem. Let's restate the problem into a more manageable question: How to wrap opaque C pointer into C++11 smart pointer (specifically unique_ptr)? Short answer: Use the  opaque C pointer object type as parameter to unique_ptr template and provide a custom deleter. That's it. If you understand the short answer, then you're done. If it's still unclear to you, then read on.

There are two kinds of unique_ptr template, one with only one template parameter (because the second parameter has default value) and one with two template parameters--see: http://en.cppreference.com/w/cpp/memory/unique_ptr. You need to use the unique_ptr template with two template parameters to wrap an opaque C pointer because you need to provide a custom deleter. A custom deleter is a function that finalize/deallocate the resources allocated by the unique_ptr constructor. Let's look at an example:

unique_ptr<FILE, int (*)(FILE*)> mFile{nullptr, closeFile};

The preceding code snippet shows the second unique_ptr template parameter is a function pointer. The function pointer is initialized with closeFile function name. In this case, the closeFile function pointer is the custom deleter. closeFunction() is a simple function which logs a message to the screen and then call fclose(), as shown in the following code snippet:

int closeFile(FILE* f) {
    cout << "Calling fclose()" << endl;
    return fclose(f);
}

You might be thinking how to obtain a valid FILE pointer in the first place, before disposing it with fclose(). Well, of course with a call to fopen(). This is how I do it:

public:
    explicit FileHandler (const char* path, const char* mode)
try:
        mPath{path}, mMode {mode}
    {
        cout << "FileHandler constructor" << endl;

        FILE* f = fopen(path, mode);

        if (f != NULL) {
            unique_ptr <FILE, int (*)(FILE*)> file{f, closeFile};
            mFile = std::move(file);

        } else {
            throw FileHandlerException(errno, "Failed to open " + string(path));
        }
    } catch (FileHandlerException& e) {

        throw e;
    }

The preceding code snippet shows that a valid FILE pointer is passed as parameter to the unique_ptr object that will manage the FILE pointer upon its initialization. Then, the object is moved to the equivalent class member which will manage the FILE pointer. You can clone the complete code at: https://bitbucket.org/pinczakko/custom-c-11-deleter

The sample shows how to wrap the opaque FILE pointer in a unique_ptr smart pointer. The FILE  pointer is an opaque "standard" C library pointer. Despite this, the technique is applicable to other opaque C pointer which usually acts as interface to a third party C library that you want to use in your C++11 application.

NOTE: The syntax of the FileHandler class constructor might be a bit alien to you if you're not familiar with C++11. It's called function-try-block, a way to wrap the whole function inside a try-catch block. The complete explanation is at: http://en.cppreference.com/w/cpp/language/function-try-block, additional heavily commented sample is at: https://msdn.microsoft.com/en-us/library/e9etx778(v=vs.120).aspx.

I hope this post is helpful to those looking to unleash the power of C libraries in C++11.

Monday, October 31, 2016

Cross Compiling Unicode Windows Application with Mingw-w64

Cross compiling Unicode Windows application in Linux is quite straight forward if you are using mingw-w64 cross compiler. All you have to do is turn on the -municode compiler switch. Other than that, you need to change your program entry point from main() to wmain() if your program is a command line program. I provided a complete sample code over at https://bitbucket.org/pinczakko/windows-event-object-test that you can read and use.

Now, let's look at the most important parts of the sample code with respect to Unicode support. First the CMakeLists.txt file. These are the necessary changes to support Unicode:
if (MINGW)
 message(status: " ** MINGW detected.. **")
 set(CMAKE_CXX_FLAGS_RELEASE "-municode ${CMAKE_CXX_FLAGS_RELEASE}")
 set(CMAKE_C_FLAGS_RELEASE "-municode ${CMAKE_C_FLAGS_RELEASE}")

 set(CMAKE_CXX_FLAGS_DEBUG "-municode ${CMAKE_CXX_FLAGS_DEBUG}")
 set(CMAKE_C_FLAGS_DEBUG "-municode ${CMAKE_C_FLAGS_DEBUG}")

# ..
endif()
The preceding code snippet shows the C++ and C compiler switch has been modified to use -municode if mingw compiler is detected.

Second, the entry point of the command line program is also modified:
int wmain( void )

The third change is the code also make use of wprintf() function in place of printf() in some places. This is one of the example:
wprintf(L"All threads ended, cleaning up for application exit...\n");
wprintf() is the "wide-character" version of printf(), well you could argue that you want to use the "tchar" version and so on. However, in this short article, the point is just to see how mingw-w64 support, I'm not trying to be extremely correct.

Thursday, October 27, 2016

What operator int() means in C++?

Short answer to the title of this post: It's a user-defined conversion to int.
Long answer: read on ;-).  The code below is a sample of the user-defined conversion. 
class MyClass {
public:
   //..
   operator HANDLE() const { return(m_hCJ); }
   //..


private: 
   HANDLE m_hCJ;          // handle to volume
   //..

};

The code above would return MyClass object's m_hCJ member value if a conversion to HANDLE type is requested. For example:
MyClass testClass;
HANDLE testHandle = testClass;
In the preceding code, testClass operator HANDLE() will be called (at runtime?) to return testClass.m_hCJ value.

For more comprehensive example and explanation, see: http://en.cppreference.com/w/cpp/language/cast_operator.

I brought this issue up because it uses the C++ operator keyword which is usually used for operator overloading. It could confuse those who hasn't seen C++ code that uses user-defined conversion.