Why might a struct store its own size? - c++

I am taking my first look into the Windows API and upon encountering WNDCLASSX I couldn't help wondering why its member, cbSize, existed. The description of cbSize, per the MSDN is: The size, in bytes, of this structure. Set this member to sizeof(WNDCLASSEX). Be sure to set this member before calling the GetClassInfoEx function. This describes it, and hints at its purpose, but I don't undestand the necessity.
My question is this: Why would a struct ever need to store its own size? Wouldn't any function handling the struct have access to that information using sizeof?

Later versions of the Windows API may add new fields to the struct. If the struct has a size, then older code can call the API function, which only copies the fields that the old code is aware of.

Related

Generic Mutator/Accessor functions

Is there a way to create generic set/get functions in C++? I have a class with a large number of attributes but no functions (ok I should probably use a struct), and really don't want to write individual set and get functions for each data member. The functions I'm thinking of would be something like 'set_member( T variable ), where T could be anything, primitive types or user defined. I imagine perhaps you could create a struct with a struct as a member, then whenever you want to access a specific member of the member struct, you refer to it by the appropriate pointer. I've tried writing something to achieve this but no luck so far.
C++ has (as far as I know) no inbuilt way to autogenerate setter/getter functions.
You might be able to work some macro-magic (with all its pitfalls), otherwise your options are slim.
I can think of following alternatives:
Some IDEs generate get, set methods automatically for the data members of class. I am not sure if it is possible for C++ IDE. But I know that Eclipse IDE for Java does it. You may check once if Eclipse IDE for C++ has this facility.
You may write a short shell script or python script for automatically generating get, set method given a text file containing names and types of variables in each line.
By default all the members of struct are public. So use struct. Or if you decide to use class, then, put all the data members in public section. If you are not doing anything other than simple set, get, then, it might be ok to do so. However, debugging will be tedious in case if you encounter issues with changes in the data members.

What's the purpose of VkStructureType? [duplicate]

In all of the create info structs (vk*CreateInfo) in the new Vulkan API, there is ALWAYS a .sType member. Why is this there if the value can only be one thing? Also the Vulkan specification is very explicit that you can only use vk*CreateInfo structs as parameters for their corresponding vkCreate* function. It seems a little redundant. I can see that if the driver was passing this struct straight to the GPU, you might need to have it (I did notice it is always the first member). But this seems like a really bad idea for the app to do it because if the driver did it, apps would be much less error prone, and prepending an int to a struct doesn't seems like an extremely computational inefficient operation. I just don't see why it exists.
TL;DR
Why do the vk*CreateInfo structs have the .sType member?
They have one so that the pNext field actually works.
Yes, the API takes a struct with a proper C type, so both the caller and the receiver agree on what type that struct is. But especially nowadays, many such structs have linked lists of structures that provide additional information to the implementation. These extension structures (though many are core in Vulkan 1.1/2) are just like all other structures, with their own sType field.
These fields are crucial because the linked lists are built with pNext pointers... which are void*s. They have no set type. The way the implementation determines what a non-NULL pNext pointer points to is by examining the first 4 bytes stored there. This is the sType field; it allows the implementation to know what type to cast the pointer to.
Of course, the primary struct that an API takes doesn't strictly need an sType field, since its type is part of the API itself. However, there is a hypothetical reason to do so (it hasn't panned out in Vulkan releases).
A later version of Vulkan could expand on the creation of, for example, command buffer pools. But how would it do that? Well, they could add a whole new entrypoint: vkCreateCommandPool2. But this function would have almost the exact same signature as vkCreateCommandPool; the only difference is that they take different pCreateInfo structures.
So instead, all you have to do is declare a VkCommandPoolCreateInfo2 structure. And then declare that vkCreateCommandPool can take either one. How would the implementation tell which one you passed in?
Because the first 4 bytes of any such structure is sType. They can test that value. If the value is VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, then it's the old structure. If it's VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO_2, then it's the new one.
Of course, as previously stated, this hasn't panned out; post-1.0 Vulkan versions opted to incorporate extension structs rather than replacing existing ones. But the option is there.

Use Fmodex callback under C++

i'm using fmodex and i'm trying to use FMOD_FILE_OPEN_CALLBACK under C++.
FMOD_RESULT F_CALLBACK FMOD_FILE_OPEN_CALLBACK(const char *name, unsigned int *filesize, void **handle, void *userdata);
But I would like to execute a method of a class. So I thought to pass current object this as userdata of the callback and execute my callback method as it's proposed here.
But unlike Fmod Studio, there is no fileuserdata in FMOD_CREATESOUNDEXINFO, only userdata pointer.
And documentation says :
[w] Optional. Specify 0 to ignore. This is user data to be attached to
the sound during creation. Access via Sound::getUserData. Note: This
is not passed to FMOD_FILE_OPENCALLBACK, that is a different userdata
that is file specific.
But how can I access this file specific pointer ? Or there is an other solution to do that ?
Thanks.
was this solved yet? If not here's how i do it.
FMOD_CREATESOUNDEXINFO* info = new FMOD_CREATESOUNDEXINFO();
info->cbsize = sizeof(FMOD_CREATESOUNDEXINFO);
// This is the field you want to set
info->fileuserdata = someUserData;
_system->createStream(file.c_str(), FMOD_DEFAULT, info, &_currentSound);
Are you using an old version of the fmod library? On my system the fileuserdata field does exist. I'm using the fmodex low level api that shipped with the fmod studio installation.
When the API in question does not provide a user data pointer for the callback, but does provide some kind of handle, as seems to be the case here, then you can forward each callback call to a C++ method (a non-static member function) in two general ways + 1 API-specific way:
use API functionality to associate a C++ object pointer with each handle, or
use a static storage std::map or std::unordered_map that associates each handle with a C++ object pointer, or
use a dynamically created trampoline function with the object address hardwired.
The third option was used e.g. in Borland's ObjectWindows framework in the 1990's, and it's generally the fastest, but it conflicts with current malware protection schemes, and since the C++ standard library doesn't support it (and as far as I know Boost doesn't support it either, although The Good Puppy over in the C++ Lounge here at SO once made a proposal about it), it's necessarily platform specific machine code.
Thus, if you don't know a way to do the first option I suggest you go with the second, a std::map or std::unordered_map that associates handles with C++ objects.
The main remaining technical hurdle is then to decide the proper time to create a map entry, and the proper time to remove it. That is highly dependent on the callback scheme. And unfortunately I have zero experience with yours, but maybe others can chime in about that detail.

C++ and FULLY dynamic functions

I have a problem with detours. Detours, as you all know, can only move among 5 bytes of space (i.e a 'jmp' call and a 4 byte address). Because of this it is impossible to have the 'hook' function in a class (a method), you cannot supply the 'this' pointer because there is simply not enough space (here's the problem more thoroughly explained). So I've been brainstorming all day for a solution, and now I want your thoughts on the subject so I don't begin a 3-5 day project without knowing if it would be possible or not.
I had 3 goals initially, I wanted the 'hook' functions to be class methods, I wanted the whole approach to be object-oriented (no static functions or global objects) and, the worst/hardest part, to be completely dynamic. This is my (in theory) solution; with assembly one can modify functions at runtime (a perfect example is any detouring method). So since I can modify functions dynamically, shouldn't I also be able to create them dynamically? For example; I allocate memory for, let's say ~30 bytes (through malloc/new). Wouldn't it be possible to just replace all bytes with binary numbers corresponding to different assembly operators (like 0xE9 is 'jmp') and then call the address directly (since it would contain a function)?
NOTE: I know on beforehand the return value, and all the arguments to all functions that I want to detour, and since I'm using GCC, the thiscall convention is practically identical to the _cdecl one.
So this is my thought/soon-to-be implementation; I create a 'Function' class. This constructor takes a variadic amount of arguments (except the first argument, which describes the return value of the target function).
Each argument is a description of the arguments the hook will receive (the size, and whether it is a pointer or not). So let's say I want to create a Function class for a int * RandomClass::IntCheckNum(short arg1);. Then I would just have to do like this:Function func(Type(4, true), Type(4, true), Type(2, false));. Where 'Type' is defined as Type(uint size, bool pointer). Then through assembly I could dynamically create the function (note: this would all be using _cdecl calling convention) since I can calculate the number of arguments and total size.
EDIT: With the example, Type(4, true) is the return value (int*), the scondType(4, true) is the RandomClass 'this' pointer and Type(2, false) describes the first argument (short arg1).
With this implementation I could easily have class methods as callbacks, but it would require an extensive amount of assembly code (which I'm not even especially experienced at).
In the end, the only non-dynamic thing would be the methods in my callback class (which also would require pre and post callbacks).
So I wanted to know; is this possible? How much work would it require, and am I way over my head here?
EDIT: I'm sorry if I presented everything a bit fuzzy, but if there is something you want more thoroughly explained, do ask!
EDIT2: I'd also like to know, if I can find the hex values for all assembly operators somewhere? A list would help a ton! And/or if it is possible to somehow 'save' the asm(""); code at a memory address (which I highly doubt).
What you describe is usually called "thunking", and is quite commonly implemented. Historically, the most common purpose has been mapping between 16-bit and 32-bit code (by autogenerating a new 32-bit function that calls an existing 16-bit one or vice versa). I believe some C++ compilers generate similar functions to adjust base class pointers to subclass pointers in multiple inheritance, also.
It certainly seems like a viable solution to your problem, and I don't foresee any huge issues. Just make sure you allocate the memory with any flags needed in your operating system to make sure the memory is executable (most modern OSs give out non-executable memory by default).
You may find this link helpful, particularly if working in Win32: http://www.codeproject.com/Articles/16785/Thunking-in-Win32-Simplifying-Callbacks-to-Non-sta
Regarding finding the hex values of assembly operations, the best reference I know of is the Appendix to the manual of the NASM assembler (and I don't just say that because I helped write it). There's a copy available here: http://www.posix.nl/linuxassembly/nasmdochtml/nasmdoca.html

C++: use of “().” and “()[].”

I am trying to understand the programming of Siemens scanner using C++ and given that my C++ skills are limited, I am having problems in understanding many parts of the code provided by the vendor.
Problem 1
For instance, the code uses reference (rMrProt) to object MrProt and notations (such as the use of use of (). and ()[].) are very confusing to me.
For instance:
ImageSamples = rMrProt.kSpace().baseResolution()
ImageSize = rMrProt.sliceSeries()[0].readoutFOV()
Some explanation of these statements would be appreciated.
All information regarding object MrProt are in “MrProt.h”, “MrProt.dll”, “MrProt.lib”. All these files have been shared at:
https://docs.google.com/open?id=0B0Ah9soYnrlIYWZkNDU2M2EtYTNmNC00YTc5LTllMzItYzIyMWU4M2ZhY2Fi
Problem 2
Also, I have been trying to read MrProt.dll and MrProt.lib without any success. Only now, I came to know of dumpbin. Any help would be appreciated.
Problem 3
Another confusion that I have is related to some part of MrProt.h itself. There is a statement in MrProt.h:
class __IMP_EXP MrProt: public MrProtocolData::MrProtDataDelegate
{
typedef MrProtocolData::MrProtDataDelegate BasicImplementation;
public:
MrProt();
MrProt(const MrProt& rSource);
…
….
}
Here, __IMP_EXP, I guess that it’s some compiler specific stuff.. some decoration etc. But, I still have no idea what to make of this.
Problem 1.
rMrProt.sliceSeries()[0].readoutFOV()
means
Take rMrProt's sliceSeries member and call that. Apparently, it returns an array-like object, something that can be indexed.
From the result, take the first element ([0]). That's some kind of object.
On that element/object, call readoutFOV.
Problem 2. You're not really supposed to read binary files. There should be documentation with them.
1)
ImageSamples = rMrProt.kSpace().baseResolution()
This is just method chaining. You call the method kSpace() on rMrPrto which returns an object, and you call baseResolution() on that object.
2) Those are binary files. What would you expect to see? To read them you'd have to be an expert in asm or at least know some low-level concepts.
3) __IMP_EXP is a common type of directive that tells the compiler that the class is either exported or imported.
It expands to _declspec(dllimport) or _declspec(dllexport), depending on whether the definition of the class is in the current module or another module.
identifier() is a method/function call
identifier[i] returns the i'th element in an array.
identifier()[i] returns the i'th element of the array returned by identifier()
I can only help on problem 1:
if the return value of rMrProt.kSpace() is a struct. instead of saving it to a struct and then access it's member you can directly access a member of his with rMrProt.kSpace().MemberName
same for rMrProt.sliceSeries() which I guess is returning an array. so rMrProt.sliceSeries()[0] will access the first value in the returning array.