C library vs WinApi - c++

Many of the standard c library (fwrite, memset, malloc) functions have direct equivalents in the Windows Api (WriteFile, FillMemory/ ZeroMemory, GlobalAlloc).
Apart from portability issues, what should be used, the CLIB or Windows API functions?
Will the C functions call the Windows Api functions or is it the other way around?

There's nothing magical about the C library. It's just a standardized API for accessing common services from the OS. That means it's implemented on top of the OS, using the API's provided by the OS.
Use whichever makes sense in your situation. The C library is portable, Win32 isn't. On the other hand, Win32 is often more flexible, and exposes more functionality.

The functions aren't really equivalent with the exception of some simple things like ZeroMemory.
GlobalAlloc for example gives you memory, but it was used for shared memory transfer under win16 as well. Parts of this functionality still exist.
WriteFile will not only write to files but to (among others) named pipes as well. Something fwrite or write can't directly do.
I'd say use c library functions if possible and use the windows functions only if you need the extra functionality or if you get a performance improvement.
This will make porting to other platforms easier later on.

It's probably more information than you're looking for (and maybe not exactly what you asked) but Catch22.net has an article entitled "Techniques for reducing Executable size" that may help point out the differences in Win32 api calls and c runtime calls.

Will the C functions call the winapi functions or is it the other way around?
The C functions (which are implemented in a user-mode library) call the WINAPI functions (which are implemented in the O/S kernel).

If you're going to port your application across multiple platforms I would say that you should create your own set of wrappers, even if you use the standard C functions. That will give you the best flexibility when switching platforms as your code will be insulated from the underlying system in a nicer way.
Of course that means if you're only going to program for Windows platforms then just use the Windows functions, and don't use the standard C library functions of the same type.
In the end you just need to stay consistent with your choice and you'll be fine.

C functions will call the system API, the Standard Runtime C Library (or CRT) is an API used to standardize among systems.
Internally, each system designs its own API directly using system calls or drivers. If you have a commercial version of Visual C++, it used to provide the CRT source code, this is interesting reading.

A few additional points on some examples:
FillMemory, ZeroMemory
Neither these nor the C functions are system calls, so either one might be implemented on top of the other, or they could even have different implementations, coming from a common source or not.
GlobalAlloc
Since malloc() is built on top of operating system primitives exposed by its API, it would be interesting to know if malloc() and direct usage of such allocators coexist happily without problems. I might imagine of some reasons why malloc might silently assume that the heap it accesses is contiguous, even if I would call that a design bug, even if it were documented, unless the additional cost for the safety were non insignificant.

Well, I'm currently trying to avoid including fstream, sstream, iostream and many C standard library files and using winAPIs instead because including any of these libraries increases the size of the output executable from about 10 KB to about 500 KB.
But sometimes it's better to use the C standard library to make your code cross-platform.
So I think it depends on your goal.

Related

How does the C++ standard library work behind the scenes?

This question has been bothering me so much for the past couple of days. I was wondering how the standard library works, in terms of functionality. I couldn't find an answer anywhere, even by checking the source code provided by the LLVM compiler which is, for a beginner like me, a really complicated piece of code.
What I'm basically trying to understand here is how does the C++ standard library work. For example let's take the fstream header file which consist of a bunch of functions that help to write to and read from files.
How does it work? Does it use the OS specific API (since the library is cross platform), or what? And, if the standard library can do it, aren't I supposed to be able to mess with some files as well without calling the standard fstream file (which to my experience I can't do)?
I apologize if my questions are unclear since I'm not a native English speaker: feel free to modify this text so as to make it clearer.
Does it use the OS specific API (since the library is cross platform), or what?
At some point, the OS specific API is used. The fstream implementation does not necessarily call an OS function directly. It might use other classes, which call functions inherited from C, etc., but eventually the call chain will lead to an OS call. (Yes, the details are often too complicated for an intermediate programmer to follow. So, as a self-described beginner, your findings are not surprising.)
The library is cross-platform in the sense that on your end (the C++ programmer), the interface is the same regardless of platform. It is not, however, the same library on every platform. Each platform has its own library, exposing the same interface on the C++ side, but making use of different OS calls. (In fact, the same platform might have multiple standard libraries, as the library implementation is provided by your toolchain, not by the standards committee.)
And, if the standard library can do it, aren't I supposed to be able to mess with some files as well without calling the standard fstream file (which to my experience I can't do)?
Yes, you are allowed to. Apparently, you have not been able to yet, but with some practice and guidance you should be able to. Everything in the standard library can be recreated in your own code. The point of the standard library (and most libraries, for that matter) is to save you time, not to enable something that was otherwise unavailable. For example, you don't have to implement a file stream for every program you write; it's in the standard library so you can focus on more interesting aspects of your project.
A compiler is just a program which create executable file or library. You can use the compiler default libraries to gain time or write your own. The default libraries communicate with the os for file operation or memory allocation and provide a simple standard classes to allow the developper to write only one code which work on all target platforms supported by the compiler and the libraries. If you want to write your own you have to write each function for all your target os.
The standard library is cross-platform in a sense that its interface does not change between platforms but its implementation does - or in practical terms - if you only use C++ and its standard library, you can write your code the same way for Linux / Windows / MacOS / Android / Whatever and if you find a C++ compiler for one of those platforms that supports the language features you used, you will be able to compile your code for that platform without rewriting anything.
So while you can use std::vector or std::fstream or any other feature in the library independently of the platform you're writing for and expect the function definitions, type names, etc. to look the same, you cannot expect the executable which you compiled for PC with Windows 10 to run on a phone with Android. You cannot even expect the same executable to run on the same PC but with different system - that is what I mean by "the implementation is different"
There are two main reasons for this difference:
Processors with different architectures (x86-64 and ARM for example) use different instruction sets and as such the C++ source would need to be compiled to a completely different machine code to run properly
Computers with processors of the same architecture which have a different operating system have different ways of dynamically allocating memory, creating files, creating streams, writing to console, creating and scheduling threads etc. - which is part of the system functionality that you use via the standard library
If you really wanted to you could use HeapAlloc() instead of operator new() or CreateThread() instead of stdlib's std::thread but that would force you to both rewrite your program every time you wanted to compile it for something else than Windows and recompile it with the target platform's compiler (and by proxy learn its API). Standard library saves you from that trouble by abstracting away those system calls.
As for the fstream in particular, here is what it uses internally on most PCs nowadays.
Basically, fstream, iostream and printf works based on a kernel function write(). When your code call printf (we use printf as an example), it will finally call write() to let the kernel work on the IO stuff. After that, write() returns and printf returns and your code continues.
So if you really want to know how the printf works internally, you have to read the source code of the Kernel.
But you shouldn't do that for now.
For a beginner, do not try to go deeper when you haven't got a basic cognition about computer. A computer is a project, just like a building. So the right way to learn it is to learn it level by level. First, learning how to use brick and cement to build a building, this is what you should do for now. What you shouldn't do is that you are learning how to build a building and this is your first time to try to use brick, then you are interested in how to produce a brick and start to focus on brick, this is a wrong way to learn IT.
If you are learning C/C++, just learn it. Remember, learn it level by level. For now, knowing how to use printf is enough.

Win32 API functions vs. their CRT counterparts (e.g. CopyMemory vs. memcpy)

In writing Win32 C/C++ code, is there any advantage (e.g. performance?) in using Windows-specific functions like lstrcpyn or CopyMemory instead of the corresponding CRT functions (aside from portability of CRT functions)?
At least some CRT functions use the Win32 functions internally. Also the CRT requires additional initialization (e.g. thread specific data for functions like strtok) and cleanup, that you might not want to have to happen.
You could create a plain Win32 application, without any dependency on anything else including the CRT (much like you could create a plain NT application using NTDLL.DLL - I think smss.exe of Windows is such a process BTW).
Having that said, I think that for most applications that doesn't matter.
UPDATE Since people seem to get so hooked up on the difference of individual functions, in particular memcpy vs. CopyMemory, I would like to add that not all functions in CRT are wrappers around those in Win32. Naturally, some can be implemented without any help from Win32 (actually memcpy is a good example for that), while others (sensibly) can't. Something that, I believe, #Merdad hinted in his answer to.
So, portability aside, I don't think performance is the next best argument for or against using the CRT.
You should choose what fits best and that typically will be the CRT. And there is nothing speaking against using individual Win32 functions (with CRT equivalents), where you seem fit.
It depends on the function and your requirements.
For things like memcpy, there isn't any point whatsoever to choosing the Windows-specific versions. Stick with standard C to keep it simple and portable.
For other things like mbstowcs, you might need to use things like MultiByteToWideChar instead -- depending on what functionality you need.
Personally I go for the C versions if possible, and only go for Win32 versions afterwards -- because there's really no reason to write Windows-specific code when it could be written portably.

Memory Editing Functions

I'm looking for functions to write and read process memory similar to the Win32API calls in windows.h but I can't seem to find any for standard C++ and I would like it to be platform independent.
There is no standard C++ API for accessing the memory of other processes. Standard C++ does not even have the concept of a 'process' at all. Moreover, the contents of the memory of other processes is highly platform-dependent, so adding a shim layer for porting to other OSes is the least of your problems.
You can get platform independent because those kinds of API calls are dependent on the OS kernel, you'd need to create wrappers for each type(read, write) and change the internal API call based on a PP define (such as _WIN32)
The C++ standard supports memcpy(), memset(), memmove(), and memcmp(). There is also and STL utility, std::copy(). These are all platform independent.
Which functions are you using on Windows? We're not sure what it is you're asking for, but if you show us what you're doing successfully there, we'll be able to help you find the equivalents on other platforms.

file handling routines on Windows

Is it allowed to mix different file handling functions in a one system e.g.
fopen() from cstdio
open() from fstream
CreateFile from Win API ?
I have a large application with a lot of legacy code and it seems that all three methods are used within this code. What are potential risks and side effects ?
Yes, you can mix all of that together. It all boils down to the CreateFile call in any case.
Of course, you can't pass a file pointer to CloseHandle and expect it to work, nor can you expect a handle opened from CreateFile to work with fclose.
Think of it exactly the same way you think of malloc/free vs new/delete in C++. Perfectly okay to use concurrently so long as you don't mix them.
It is perfectly OK to use all of these file methods, as long as they don't need to interact. The minute you need to pass a file opened with one method into a function that assumes a different method, you'll find that they're incompatible.
As a matter of style I would recommend picking one and sticking to it, but if the code came from multiple sources that may not be possible. It would be a big refactoring effort to change the existing code, without much gain.
Your situation isn't that uncommon.
Code that is designed to be portable is usually written using standard file access routines (fopen, open, etc). Code that is OS-specific is commonly written using that OS's native API. Your large application is most likely a combination of these two types of code. You should have no problem mixing the file access styles in the same program as long as you remember to keep them straight (they are not interchangeable).
The biggest risk involved here is probably portability. If you have legacy code that has been around for a while, it probably uses the standard C/C++ file access methods, especially if it pre-dates the Win32 API. Using the Win32 API is acceptable, but you must realize that you are binding your code to the scope and lifetime of that API. You will have to do extra work to port that code to another platform. You will also have to re-work this code if, say, in the future Microsoft obsoletes the Win32 API in favor of something new. The standard C/C++ methods will always be there, constant and unchanging. If you want to help future-proof your code, stick to standard methods and functions as much as possible. At the same time, there are some things that require the Win32 API and can't be done using standard functions.
If you are working with a mix of C-style, C++-style, and Win32-style code, then I would suggest separating (as best as is reasonably possible) your OS-specific code and your portable code into separate modules with well-defined APIs. If you have to re-write your Win32 code in the future, this can make things easier.

Unmanaged C++: How to dynamically load code?

Our industry is in high-performance distributed parallel computing. We have an unmanaged C++ application being developed using Visual Studio 2008.
Our application (more like a framework) is supposed to be able to dynamically load code (algorithms) developed by 3rd parties (there can be many dlls) that conforms to our interface specification, and calls the loaded code to get some results.
Think of it like you want to call a sin(x) function, but there are many different implementations of sin(x) that you could use.
I have a few questions as I'm very new to this area of dynamically loading code:
Is dll (dynamic-link library) the answer to this type of requirement?
If the 3rd-party used a different type of IDE to create the dll compared to mine (say Eclipse CDT, C++Builder, Visual C++ 6.0, etc), would the dll still work with my application?
Our application is supposed to work cross-platform as well (should be able to run on Linux), would using QLibrary be the most logical way to abstract away all the platform-specific dll loading?
(OPTIONAL) Are there some unforeseen problems that I might encounter?
1) generally, yes. If the API gets complex and multi-object, I'd use COM or a similar mechanism. But if you have to manage only a little state, or can go completely state-free, a pure DLL interface is fine.
2) Use a suitable calling convention (stdcall) and data types. I would not even asusme that the implementation has to be in C++. so that means char/wchar_t, explicit-sized ints, e.g. int32 , float and double, and C-style arrays of them.
3) can't say
4)
No cross-boundary memory allocations: free what you allocate, and let the plugin free what it allocated.
Your API design has a big influence on achievable performance and implementation effort. DOn't make the functions to small, give the implementation some freedom how it handles certain things, define error protocol, threading requirements etc.
[edit]
Also, if you declare structures, look into alignment and compiler options to control this (usually #pragma pack). This is required so clients see the same layout.
The compiler usually "mangles" the names for the exported symbols (e.g. add an udnerscore for STDCALL convention). Typically, this is controlled through a .def file that is passed to the linker.
Yes, it is. But there are many issues.
May or may not. Firstly, you should be aware of calling conventions. Secondly, since there is no standardized ABI for C++, you should stick to plain C at interface level (Btw, COM technology was all about this -- making a standardized ABI). Thirdly, each plugin may have its own CRT and so problems may appear, there is a good article about this on MSDN.
Yes, this will help with loading dynamic libraries, but not with problems in (2). Althought, these problems mostly windows specific.
In my experience, QLibrary is the best answer to your questions.
It provides a simple interface and takes care of all the platform-specific details.
Indeed, that means that the plugins must be also written using QT.