How do I create an array of namespaces? - arrays

How can I create an array of namespaces? And because it seems like a long shot, if this is impossible, is there something similar to a namespace that can be made into an array?
The namespace, if it helps, contains these variables:
const int maxx=// depends on the particular namespace
// I need an array to go through each namespace and
// pick out the variable
const int maxy=// depends on particular namespace
//prgm is a class I made
prgm sector[maxx][maxy];
// another array of prgms. int is my shorthand of saying "depends on
// particular namespace", so is char.
prgm programs[int]={prgm1(int,int,char),prgm2(int,int,char)...
So any help would be welcome.

You could use reflection, but I think you should rethink your design.

I am not sure what language you are talking about, but in many (most?) languages, references to constants are replaced by the constant value at compile time. So they are no longer present at runtime and even reflection won't help.
You could create a class in each namespace that exposes the constants as (static) properties. Then you can use reflection to search the class in each namespace and obtain the constant values from the properties.
But, as mentioned by others, you should really rethink your design. Finally, namespaces are usually not accessable via reflection because they just extend the class names of the contained classes (and other stuff). Or is there a (non-esoteric) language that exposes namespaces as entities via reflection?
For .NET the reference for the System.Type.Namespace property states the following.
A namespace is a logical design-time naming convenience, used mainly to define scope in an application and organize classes and other types in a single hierarchical structure. From the viewpoint of the runtime, there are no namespaces.

Is this supposed to be C++? Sounds like you need to define a class, not a namespace, then create instances (objects) of that class and put them in an array.
So the sector variable gets tricky, since it is sized based on the value of maxx and maxy parameters that would be passed to the constructor of the class. You can take care of that problem by using a container class or a dynamically-allocated multi-dimensional array instead.

If you talk about C++, in there you can't pass namespaces as entities around. But you can do so with types, as type argument to templates. In this case, an MPL sequence could help together with MPL algorithms:
struct c1 { typedef int_<2> value_x; };
struct c2 { typedef int_<3> value_x; };
struct c3 { typedef int_<1> value_x; };
template<typename C> struct get_x : C::value_x { };
typedef vector<c1, c2, c3> scope_vec;
typedef max_element<
transform_view< scope_vec , get_x<_1> >
>::type iter;
You may then create your array like
prgm programs[deref< iter >::type::value];
Note that the search within that type-vector happens at compile time. So the value of the array is determined at compile time either.

Related

How to have two structs with same type and name in different header files without conflicts?

I already have, say, a struct smallbox with two primitive variables (int identifier, int size) in it. This smallbox is part of higher structs that are used to build i.e. queues.
Now, I have in a part of my project an issue for which I came up with the solution to expand this smallbox, so it has another piece of information like int costs_to_send_it. While, I am not allowed to change my basis structs, is there a way to expand this struct in some fashion like methods overloading in java or so? Will I still be able to use all operation that I have on my higher structs while having the new struct smallbox with the new attribute inside instead of the old one?
This sentence determines the answer: “[Will] I still be able to use all operation that I have on my higher structs while having the new struct smallbox with color attribute inside instead of the old one?” The answer is no.
If the headers and routines involved were completely separate, there are some compiling and linking “games” you could play—compiling one set of source files with one definition of the structure and another set of source files with another definition of the structure and ensuring they never interacted in ways depending on the structure definition. However, since you ask whether the operations defined using one definition could be used with the alternate definition, you are compelling one set of code to use both definitions. (An alternate solution would be to engineer one source file to use different names for its routines under different circumstances, and then you could compile it twice, once for one definition of the structure and once for another, and then you could use the “same” operations on the different structures, but they would actually be different routines with different names performing the “same” operation in some sense.)
While you could define the structure differently within different translation units, when the structure or any type derived from it (such as a pointer to the structure) is used with a routine in a different translation unit, the type the routine is expecting to receive as a parameter must be compatible with the type that is passed to it as an argument, aside from some rules about signed types, adding qualifiers, and so on that do not help here.
For two structures to be compatible, there must be a one-to-one correspondence between their members, which must themselves be of compatible types (C 2018 6.2.7 1). Two structures with different numbers of members do not have a one-to-one correspondence.
is there a way to expand this struct in some fashion like methods
overloading in java or so?
In method overloading, the compiler chooses among same-named methods by examining the arguments to each invocation of a method of that name. Observe that that is an entirely localized decision: disregarding questions of optimization, the compiler's choice here affects only code generation for a single statement.
Where I still be able to use all operation
that I have on my higher structs while having the new struct smallbox
with color attribute inside instead of the old one?
I think what you're looking for is polymorphism, not overloading. Note well that in Java (and C++ and other the other languages I know of that support this) it is based on a type / subtype relationship between differently-named types. I don't know of any language that lets you redefine type names and use the two distinct types as if they were the same in any sense. Certainly C does not.
There are some alternatives, however. Most cleanly-conforming would involve creating a new, differently-named structure type that contains an instance of the old:
struct sb {
int id;
int size;
};
struct sb_metered {
struct sb box;
int cost;
}
Functions that deal in individual instances of these objects by pointer, not by value, can be satisfied easily:
int get_size(struct sb *box) {
return sb->size;
}
int get_cost(struct sb_metered *metered_box) {
return metered_box->cost;
}
int main() {
struct sb_metered b = { { 1, 17}, 42 };
printf("id: %d, size: %d, cost: %d\n",
b.id,
get_size(&b.box),
get_cost(&b));
}
Note that this does not allow you to form arrays of the supertype (struct sb) that actually contain instances of the subtype, nor to pass or return structure objects of the subtype by value as if they were objects of the supertype.

Designing a simple GUI framework in C [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I need to design, for a school project, a very simple GUI framework which needs to support the following controls/widgets: Window, Panel, Image, Label and Button.
The first question that came up to my mind is whether or not Window should be a control. I think it suppose to.
We have Window and Panel which can contain other controls. Button, Label and Image, cannot. So we need two basic types of controls; One which is a container and another which is not (I've seen that in Gtk implementation the later is also a container, but can only contain one single child. It's called GtkBin. I think it's an overhead for my simple project.
Third issue I came across with is: I need to traverse the UI tree (for the drawing) but since there's no mechanism for polymorphism in C, it's becoming somewhat problematic.
I thought about the following solution, utilizing union. Basically I'll need some function to convert a generic Control to it's actuall type.
typedef struct button {
char *image_path;
} Button;
typedef struct control_node {
Control *node;
struct control_node *next;
} ControlNode;
typedef struct panel {
ControlNode *children;
} Panel;
typedef union control_data {
Panel panel;
Button button;
} ControlData;
typedef struct control {
int x;
int y;
int type;
ControlData *data;
} Control;
So I'd like to get your thoughts about the issues I've introduced and an opinion about my current strategy (I am NOT looking for an implementation, rather thoughts/ideas etc)
Thanks.
You should put a void * first thing in the layout of every "GUI class" that will point to manually implemented v-tables for every type. The first function in every type's v-table could be one, returning a unique integer for every type (or just be a unique integer), so you can tell what is what and have some type safety implemented. Although it is not necessary, you could use the v-table pointer value to determine the type (since it will be unique), which will save on memory, but will be a little less obvious. It is also crucial to have virtualism in the object destruction, so a destructor function for handling each unique type's internals with its position in the v-table being consistent is also a must. Although for your task this might actually be avoidable, but for production it is a must.
As for the actual tree, this should be built on a simple parent-child relation, revolving around a leaf and node interface, the leaf only holding a pointer to the parent, the node also including a dynamic list type you must also implement. Then traversing the tree is fairly straightforward.
You can modularize a bit by using "interfaces" structs and aggregation in lieu of inheritance, but it won't save you much effort compared to implementing every type on its own, as long as you keep the v-table pointer the first object in the type layout, so that you know what you are working with and how to use it. The layout of the rest is not that crucial to follow any guidelines, as long as you know the type and cast the pointer to the appropriate struct type. But since every object will have a parent, even the root, which will be identifiable by its parent being 0, you really should put the parent second after the v-table pointer, this way you can avoid casting when all you need to access is the parent.
Another thing you can benefit from is using signals, as in have another pointer in every button, so you can assign it to a function to be executed when you "click" the button.
There are 2 different problems here: the conception of the GUI and its implementation in C. If conception is simpler in OO model, just write it that way. As first C++ compiler were just preprocessors for C code, C can implement OO modeling with the use of vtables.
First define clearly what are your objects (classes): which can be containers, which are drawables, which can react to mouse or keyboard events. What are their properties: text, x-y coordinates, bitmaps, and probably a z-coordinate. At the end of that phase, you should have a hierachy of classes with properties and methods, and possible overrides in subclasses - if you have learned it, UML could help for that part.
Second, you will have to implement that in C. Don't worry about it. You will not have the syntactic sugar of copy and move constructors for free, nor the notion of public, private and protected attributes, but struct can contain sub-objects, pointers to other structs and pointer to functions.
You just need a lexicon to translate OO tools in C :
class: struct
field of class: field of struct
method of class: function whose first attribute is a pointer to an instance of the struct
virtual method : pointer to a method
constructor and destructor : special methods that must be called explicitely - no automatic destruction if a struct goes out of scope
A non final class (contains virtual methods) should contain a VTABLE, which is a mere array of pointers to the virtual methods. This VTABLE should be first element of struct to ease class pointer casting. A derived class first contains its own vtable (if it is not final), then its attributes and then an instance of its parent. A cast from parent to derived pointer is just a matter of adding an offset. If you need multiple inheritance, you add the other parents after the first in the struct. Virtual inheritance would be slightly tougher to implement because it involves pointers in the VTABLE. Same if you need class aware objects, just add a constant in the VTABLE. But I do not think that you need all that for your requirement.
So look twice if you really want the harder bits: multiple inheritance and class aware objects, then just implement each class in its .h + .c file. You even get for free private methods: they are just static functions.

GObject OOP Syntax

I'm looking for a GObject cheat sheet, how common OOP concepts map to GObject's facilities. Consider for example:
AnyGObject *o;
o = anygobject_new();
Now, what are the conventions for...
calling a method
calling a method declared by a base class
calling a method declared by an interface the class is implementing
calling a class method
calling a class method declared by a base class
calling a virtual method
casting to a base class
casting to a derived class
casting to an interface the class is implementing
testing whether an object is of a particular type
...
Clarification:
The GObject Reference Manual and GObject HowTo explain at length how to create a new class (class struct, object struct, private struct, various macros, conventions). Taken together these facilities allow for OOP. Yet there seems to be no tutorial on how to use them consistently.
This answer assumes you are working with C. Other (usually object-oriented) languages have special bindings built to make working with GObject seem more natural.
If you've worked with GTK+, you already have done much of that list.
GObject methods are not members themselves (there is a vtable of sorts but it's only used for assigning virtual method implementations in a derived class when the class is first created). Instead, all methods in GObject are just plain functions, usually(?) prefixed by a method name prefix, and with the this pointer as the first argument.
For example, the C++ method
namespace Lib { // short for Library; to demonstrate GObject's idiomatic naming conventions
class Foo {
public:
void Bar(int z);
};
}
would be a plain function in the global namespace declared as
void lib_foo_bar(LibFoo *foo, int z);
and you would call it directly, just like any other C function.
Class derivation in GObject occurs by having the full data structure of the parent class as the first member of the derived class's data structure. For various reasons pertaining to rarely-discussed clauses in the C standard (and possibly the System V ABI and implementation of gcc, clang, and even the Microsoft C compilers), this means that a pointer to an object of the derived class is equivalent to a pointer to the parent class!
So if LibBaz derives from LibFoo, all you would need to say is
LibFoo *foobaz = (LibFoo *) baz;
and the same applies in reverse:
LibBaz *bazfoo = (LibBaz *) foo;
(This latter approach is what GTK+ uses for GtkWidget; I don't know if other GObject libraries do the same thing.)
Idiomatic GObject declarations include a bunch of macros that make the type conversions more terse while at the same time adding runtime type safety checks. Our LibFoo class would have the following macros:
#define LIB_TYPE_FOO (lib_foo_get_type())
#define LIB_FOO(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), LIB_TYPE_FOO, LibFoo))
With this, we would instead say
LibFoo *foobaz = LIB_FOO(baz);
LibBaz *bazfoo = LIB_BAZ(foo);
and if either baz or foo isn't the correct type for the conversion, a warning will be logged to standard error, which you can break at and investigate using a debugger.
(The lib_foo_get_type() function (and LIB_TYPE_FOO neatness macro) is important: it returns a numeric ID that maps to the type of LibFoo for future reference. If LibFoo doesn't have such a mapping, it will create the mapping, registering the type and creating the virtual method mappings.)
A similar macro allows type checking:
#define LIB_IS_FOO(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), LIB_TYPE_FOO))
which is a simple expression that can be used in an if statement.
So what about calling parent class methods? Well, if we put all of the above together, we have the answer:
lib_foo_parent_method(LIB_FOO(aLibBazInstance), params);
The same applies to virtual methods. Virtual methods are implemented using the GObject approximation to vtables and are transparent to the end programmer. All you will do is
lib_foo_virtual_method(LIB_FOO(whatever), params);
(If you actually build the derived class itself, the how of virtual methods becomes important.)
There are no static methods in GObject, because methods aren't tied to a class as closely as they are in real object-oriented languages. Just create a top-level method in your library:
void lib_something_common(params);
Finally, all of the above applies to interfaces. Interfaces work the exact same way to the end user; they use the same
void lib_iface_method(LibIface *iface, params);
approach to method calling, the same casting rules, and the same LIB_IFACE() and LIB_IS_IFACE() helper macros.
Hopefully that helps! Any further explanation would have to tread into explaining how to create a GObject, which I tried to keep outside the scope of this answer for simplicity's sake, but is a useful thing to know anyway.

Recursive visibility of symbols in Ada packages

Let's say I have a generic vector library. To make it easier to use, I want to instantiate various common forms of the vector library and make them visible in a single package.
I'm trying this:
with GenericVector;
package Vectors is
package Vectors3 is new GenericVector(3);
use all type Vectors3.Vector;
subtype Vector3 is Vectors3.Vector;
package Vectors4 is new GenericVector(4);
use all type Vectors4.Vector;
subtype Vector4 is Vectors4.Vector;
end;
The end goal is that I want to be able to do with Vectors; use Vectors; and end up with Vector3 and Vector4 types directly available which Just Work.
Naturally, the code above doesn't work. It looks like the use all type statements import the definitions attached to the specified type into the package specification but then those definitions aren't exported to the user of Vectors. I have to do with Vectors; use Vectors; use all type Vectors.Vectors3; instead. This is kind of sucky.
How can I do this?
You could simply make Vector3 and Vector4 new types, and not just subtypes. That would implicitly declare all the inherited, primitive operations from GenericVector in Vectors.
use Vectors gives you direct visibility to those identifiers that are declared in Vectors, including those that are declared implicitly. (Implicit declarations are things like "+", "-", operators when you declare a new integer type, and inherited operations when you declare a derived type.) But it doesn't give you direct visibility to anything else. In particular, use is not transitive, because use all type Vectors3.Vector does not declare any new identifiers in Vectors.
You could accomplish this by declaring renaming identifiers for everything that you want a use Vectors user to see. (For types, you'd have to use subtype since there's no type renaming in Ada.) E.g. in Vectors:
function Dot_Product (V1, V2 : Vectors3.Vector) return Float
renames Vectors3.Dot_Product;
(I'm just guessing at what the operations in GenericVectors might look like.) Now, anywhere that says use Vectors will be able to use Dot_Product directly. You'd have to do something like this for every identifier, though. If there are a lot of them, this probably isn't a viable solution. (The renaming declaration doesn't have to use the same name Dot_Product.)
Although it may seem annoying that you can't get this kind of transitive visibility, the alternative probably would turn out to be more annoying, because you can't look at Vectors and see what identifiers would be made visible by use Vectors; the result would probably be either unexpected name conflicts or other surprises.

how to program high level concepts (i.e. Object class, and Generics) in C

Here lately I've been tinkering around with my own languages as well as reading various writings on the subject.
Does anyone have any good advice on how, in C (or Assembler), do you program the concept of the Object Class and/or the concept of Generics into a language. (referring to the Java implementations of Object and Generics)
For instance, in Java all all classes extend Object. So how do you represent this at the C level? is it something like:
#include <stdio.h>
typedef struct {
int stuff;
} Object;
typedef struct {
int stuff;
Object object;
} ChildClass;
int main() {
ChildClass childClass;
childClass.stuff = 100;
childClass.object.stuff = 200;
printf("%d\n", childClass.stuff);
printf("%d\n", childClass.object.stuff);
}
And I'm not really even sure how to get started with implementing something like Generics.
I also appreciate any valuable links regarding program langauge design.
Thanks,
Take a look at Structure and Interpretation of Computer Programs by Abelson and Sussman. While it doesn't show how to do it in C, it does demonstrate how to create types at run time and how to build an object system on top of a language that doesn't provide native support. Once you understand the basic ideas, you should be able to use structs and function pointers to create an implementation. Of course, looking at the source code for a C++ preprocessor will also be instructive. At one time, C++ was just a preprocessor for a C compiler.
I found this book a little while ago that has been an interesting read: Object-Oriented Programming With ANSI-C (PDF).
In C I've created class-like structures and methods by using structs (to store the class's state) and functions that take pointers to them (methods of the class). Implementing things like inheritance is possible, but would get messy fast. I'm not a Java guy though, and I'm not sure how much of Java you should press onto C, they are very different languages.
Here's probably the crudest form of a object implementation possible; I wrote it to run multiple PID controls at the same time.
//! PID control system state variables
typedef struct {
const PID_K * K; //!< PID control parameters
int32_t e; //!< Previous error (for derivative term)
int32_t i; //!< Integrator
} PID_SYS;
void PID_Init(PID_SYS * sys, const PID_K * K)
{
sys->i = 0;
sys->e = 0;
sys->K = K;
}
int16_t PID_Step(PID_SYS * sys, int32_t e)
{
// ...PID math using "sys->" for any persistent state variables...
}
If your goal is to write a new language that incorporates high level concepts, you might want to look at the CPython sources. CPython is an object oriented programming language whose interpreter is written in C. Open source C implementations of compilers/interpreters for C++, D, Javascript, Go, Objective C, and many, many others exist as well.
It's more complicated, but you're on the right path. Actual implementations use roughly the same code as yours to achieve inheritance (but they actually use containment to do it, which is quite ironic), along with a per-instance table of function pointers (virtual functions) and some (okay, many) helper macros.
See gobject.
It's definitely not C, but I'd recommend taking a look at Lua.
At its core, Lua only has a few basic types: number, string, boolean, function, and table (there's a couple more outside of the scope of this topic, though. A table is essentially just a hashtable that accepts keys of any type and can contain values of any type as well.
You can implement OOP in Lua by way of metatables. In Lua, a table is allowed to have up to one metatable, which is accessed under special circumstances, such as when a table is added or multiplied to another table or when you try to access a key that is not present in the table.
Using metatables, you can quickly and easily achieve something quite like inheritance by chaining together multiple metatables. When you try to access a missing key in a table, Lua looks up a key named __index in that table's metatable. So if you try to access a key named foo on a table that doesn't have such a key, Lua will check for foo in the first metatable. If it isn't present there and that metatable has a metatable of its own with __index defined, it will check for foo in the next one, and so on.
Once you realize how simple it is to do this in Lua, translating it to C is very achievable. Your OOP will be completely at run-time, of course, but it will be very OOP-like indeed.

Resources