Implementing dynamic typing in C [duplicate] - c

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Representing dynamic typing in C
A professor at my History of Computation side-lecture went into great depth about manifestly typed or type-inferred languages and generally praised the greatness of latently typed languages (faster dev times, dynamic systems, etc...).
The same day, at an Automata Class, another prof says:
Dynamic typing makes things more complex by adding more ways to do the same thing.
I've been using statically typed languages most of my life : C/C++/Java - my only exposure to the other has been Shell Coding and Ren'Py.
My question is, can I write a simple program in C that implements some of the benefits of both ?
For instance, I could create Unions to accept all user driven data, like so :
typedef union {
int int_type;
char char_type;
//and so on
} dynamic;
// Var Creation :
dynamic data;
// For unknown return type
void* function(dynamic data);
I realize a Union could compromise type-safety, but that is what I'm trying to do here. What other approach could I take ? I'm just trying for a demonstration.
I tried for an answer from this question. But honestly, I could not follow the arguments closely.
I apologize if the question seems silly.
PS
Using suggestions from below, I wrote this : http://codepad.org/A9JAX8lD, which basically does nothing much dynamic, but is at least a start.
I think I see what both my professors were trying to say.

My suggestion is not to try doing dynamic typing in a statically typed language. It will most likely have sub-par performance and a very strong syntactical burden. Instead, if you only ever have experienced statically typed languages, I would strongly suggest trying out Python. It is highly dynamic and will teach you new ways of thinking.
And last but not least, there also is Cython which is a Python dialect using C as intermediate language. It can mix static typing and dynamic typing, it's really refreshing.

I'm not against types, but I don't know of any type systems that aren't a complete pain [...]
-- Alan Kay
It's quite possible to implement a fully-featured dynamic type system on top of C: Take GType, on which the GLib Object System is based.
However, such systems are often painful to use because of the amount of boilerplate code they need, which can be worked around by using custom code generators and preprocessors, which is how Objective-C got started.

If you want to show how C can be "not type safe" try using void* to pass arguments. The downside is that it's not truly dynamic since you cannot call any methods on the object without casting it first.

Related

What are static and dynamic binding in C (strictly C,not C++)?

I had initial apprehensions about posting this question lest it be a duplicate.But even after googling with many keywords,I couldn't find any link on StackOverflow that explains static and dynamic binding for C.There are questions and answers for C++ though,but all involve classes and stuff that are clearly not for C.And the links outside StackExchange were quite dubious.
I need to know the rigorous definition and contrast between these two bindings,exclusively in the context of C.I would appreciate if you can take some time to answer it,or give me the links on StackOverflow for this lest I am mistaken and it has been answered in detail before.
I intend to have a clear idea about:
Binding in C.
Static vs dynamic binding in C.
Edit It would be immensely helpful if you could explain the difference with some simple code snippets.
Formally, there are no such terms in "native" C.
Simplified explanation of the terms static binding ("early binding") and dynamic binding ("late binding"): they are most often used in object-orientated design, to determine whether the decision to call a particular inherited member function is done at compile time or in run time.
The meaning of a virtual function is that it's an inherited function which gets called instead of the equivalent function in the base class which was inherited. If the compiler can determine whether an object is of type "base class" or type "inherited class" at compile time, you get static binding, otherwise dynamic binding. So you would need some sort of runtime type information (RTTI).
In the above context, these terms only make sense if you are using object-oriented inheritance/polymorphism in your C program. C has no language support for such mechanisms. It is possible to implement them "manually" in C, but it is tedious and the code tends to be quite a mess. For those who insist, there is a book "Object oriented design in ANSI-C" which demonstrates how it can be done.
(Personally I would not recommend that book, nor to implement polymorphism in C. If you need those OOP feaures, just code in C++.)
C is a statically compiled language, it doesn't really have "dynamic binding".
You can do it manually using API:s such as POSIX' dlopen(), but I would hesitate to call that "binding" although in a sense I guess it is.

Can I use C for Object Oriented Programming? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Can you write object oriented code in C?
Can I use C(not C++!!!) for Object Oriented Programming?
Yes! Object Oriented Programming is A Good Thing, and is very, very possible in C.
Creating objects is not limited to C++ or any other language. Data hiding is easier with C++ and other fourth-generation languages, and having languages that automagically clean up after themselves makes programming easier. BUT! There's always an overhead cost for making the programmer's life easier.
Using pointers to structures is one easy way to implement OOP in C. Linked lists spring to mind immediately. For a (voice)mail system, you could have a mailbox struct that "contained" message structs (as well as the mailbox's own data, of course). Hiding the implementation of a message would be easy; all you'd have to know is that the message had pointers to its mailbox, the previous message, and the next message. Of course, you'd know that a certain set of functions would operate on a mailbox and another set that worked with a message.
The advantage C++ has over C when it comes to OOP is that C++ easily enables you to put methods (actually pointers to them!) into objects. In truth, the methods are just special cases of objects....
There is a book: "Object-Orientated Programming with ANSI-C".
I was always under the impression that you couldn't. This is why: C++ was originally called "C with Objects." There might be a way to, in effect, fake OOP C, but I don't think that it's strictly 100% OOP.
greater minds will be able to clarify this, though
It is a matter of discipline, and you have to build your own framework AND stick to it.
You will have a lot of "syntactical sugar" and you won't have the beauty of expression that a well designed OOP language has. But yes, you can.
Even polymorphism is possible, but you have to write and maintain the appropriate code by yourself.
STRING to_string(OBJECT o)
{
switch get_class(o) {
case CLASS_OBJECT:
return "object";
break;
default:
return "something";
break;
}
}
...

C for an Object-Oriented programmer

Having learned Java and C++, I've learned the OO-way. I want to embark on a fairly ambitious project but I want to do it in C. I know how to break problems down into classes and how to turn them into class hierarchies. I know how to abstract functionality into abstract classes and interfaces. I'm even somewhat proficient at using polymorphism in an effective way.
The problem is that when I'm presented with a problem, I only way I know how to do it is in an Object-Oriented way. I've become too dependent on Object-Oriented design philosophies and methodologies.
I want to learn how to think in a strictly procedural way. How do I do things in a world that lacks classes, interfaces, polymorphism, function overloading, constructors, etc.
How do you represent complex concepts using only non-object-oriented structs? How do you get around a lack of function overloading? What are some tip and tricks for thinking in a procedural way?
The procedural way is to, on one side, have your data structures, and, on the other, your algorithms. Then you take your data structures and pass them to your algorithms. Without encapsulation, it takes a somewhat higher amount of discipline to do this and if you increase the abstraction level to make it easier to do it right, you're doing a considerable part of OO in C.
I think you have a good plan. Doing things the completely OO way in C, while quite possible, is enough of a pain that you would soon drop it anyway. (Don't fight the language.)
If you want a philosophical statement on mapping the OO way to the C way, in part it happens by pushing object creation up one level. A module can still implement its object as a black box, and you can still use reasonable programming style, but basically its too much of a pain to really hide the object, so the caller allocates it and passes it down, rather than the module allocating it and returning it back up. You usually punt on getters and setters, or implement them as macros.
Consider also that all of those abstractions you mentioned are a relatively thin layer on top of ordinary structs, so you aren't really very far away from what you want to do. It just isn't packaged quite as nicely.
The C toolkit consists of functions, function pointers and macros. Function pointers can be used to emulate polymorphism.
You are taking the reverse trip old C programmers did for learning OO.
Even before c++ was a standart OO techniquis were used in C.
They included defining structs with a pointer to srtuct (usually called this...)
Then defining pointer functions in the struct, and during runtime initialize those pointers to the relevant functions.
All those functions received as first paremeter the struct pointer this.
Don't think C in the complete OOP way. If you have to use C, you should learn procedural programming. Doing this would not take more time than learning how to realize all the OOP features in C. Furthermore, basic encapsulation is probably fine, but a lot of other OOP features come with overhead on performance when you mimic them (not when the language is designed to support OOP). The overhead may be huge if you strictly follow the C++ design methodology to represent every small things as objects. Programming languages have specific purposes in design. When you break the boundary, you always have to pay something as the cost.
Don't think you have to shelve your knowledge of object-oriented work - you can "program into the language".
I had to work in C after being primarily experienced in object-oriented work. C allows for some level of object concepts to pull through. At the job, I had to implement a red-black tree in C, for use in a sweep-line algorithm to find the intersection points in a set of segments. Since the algorithm used different comparison functions, I ended up using function pointers to achieve the same effect as lambdas in Scheme or delegates in C#. It worked well, and also allowed the balanced tree to be reusable.
The other feature of the balanced tree was using void pointers to store arbitrary data. Again, void and function pointers in C are a pain (if you don't know their ins and outs), but they can be used to approximate creating a generic data structure.
One final note: use the right tool for the job. If you want to use C simply to master procedural technique, then choose a problem that is well-suited to a procedural approach. I didn't have a choice in the matter (legacy application written in C, and people demand the world and refuse to enter the 21st century), so I had to be creative. C is great for low/medium abstractions from the machine, say if you wanted to write a command-line packet inspection program.
The standard way to do polymorphic behavior in C is to use function pointers. You'll find a lot of C APIs (such as the standard qsort(3) and bsearch(3)) take function pointers as parameters; some non-standard ones such as qsort_r take a function pointer and a context pointer (thunk in this case) which serves no purpose other than to be passed back to the callback function. The context pointer functions exactly like the this pointer in object-oriented languages, when dealing with function objects (e.g. functors).
See also:
Can you write object-oriented code in C?
Object-Orientation in C
Try not to use OOP in C. But if you need to, use structures. For the functions,
take a structure for an argument, like so:
typedef struct{
int age;
char* name;
char* dialog;
} Human;
void make_dialog(Human human){
char* dialog="Hi";
human.dialog=dialog;
}
which works exactly like python's self, or something like that and to access other functions belonging to that class:
void get_dialog(Human human){
make_dialog(human);
printf(human.dialog);
}

What are the pitfalls and gotchas of mixing Objective-C and C?

At the risk of oversimplifying something I'm worried might be ridiculously complex, what should I be aware of when mixing C and Objective-C?
Edit: Just to clarify, I've never worked with C before, and I'm learning Objective-C through Cocoa. Also I'm using the Chipmunk Dynamics engine, which is C.
I'd put it the other way around: you might be risking overcomplicating something that is ridiculously simple :-)
Ok, I'm being a bit glib. As others are pointing out, Objective-C is really just a minimal set of language extensions to C. When you are writing Objective-C code, you are actually writing C. You can even access the internal machinations of the Objective-C runtime support using some handy C functions that are part of the language (no... I don't recommend you actually DO this unless you really know what you're doing).
About the only time I've ever had mildly tricky moments is when I wanted to pass an Objective-C instance method as a callback to a C function. Say, for example, I'm using a pure-C cross platform library that has functions which accept a callback. I might call the function from within an object instance to process some data, and then want that C function to call my instance BACK when its done, or as part of getting additional input etc etc (a common paradigm in C). This can be done with funky function wrapping, and some other creative methods I've seen, and if you ever need to do it googling "objective-c method for c callback" or something like that will give you the goods.
The only other word of advice is to make sure your objects appropriately manage any manually malloced memory that they create for use by C functions. You'll want your objective-c classes to tidy up that memory on dealloc if, indeed, it is finished.
Other than that, dust off any reference on C and have fun!
You can't 'mix' C and Objective-C: Objective-C is a superset of C.
Now, C++ and Objective-C on the other hand...
Objective C is a superset of C, so it shouldn't conflict.
Except that, as pointed here pure C has different conventions (obviously, since there is no built-in mechanism) to handle OO programming. In C, an object is simply a (struct *) with function pointers.

How should I structure complex projects 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 have little more than beginner-level C skills and would like to know if there are any de facto "standards" to structure a somewhat complex application in C. Even GUI based ones.
I have been always using the OO paradigm in Java and PHP and now that I want to learn C I'm afraid that I might structure my applications in the wrong way. I'm at a loss on which guidelines to follow to have modularity, decoupling and dryness with a procedural language.
Do you have any readings to suggest? I couldn't find any application framework for C, even if I don't use frameworks I've always found nice ideas by browsing their code.
The key is modularity. This is easier to design, implement, compile and maintain.
Identify modules in your app, like classes in an OO app.
Separate interface and implementation for each module, put in interface only what is needed by other modules. Remember that there is no namespace in C, so you have to make everything in your interfaces unique (e.g., with a prefix).
Hide global variables in implementation and use accessor functions for read/write.
Don't think in terms of inheritance, but in terms of composition. As a general rule, don't try to mimic C++ in C, this would be very difficult to read and maintain.
If you have time for learning, take a look at how an Ada app is structured, with its mandatory package (module interface) and package body (module implementation).
This is for coding.
For maintaining (remember that you code once, but you maintain several times) I suggest to document your code; Doxygen is a nice choice for me. I suggest also to build a strong regression test suite, which allows you to refactor.
It's a common misconception that OO techniques can't be applied in C. Most can -- it's just that they are slightly more unwieldy than in languages with syntax dedicated to the job.
One of the foundations of robust system design is the encapsulation of an implementation behind an interface. FILE* and the functions that work with it (fopen(), fread() etc.) is a good example of how encapsulation can be applied in C to establish interfaces. (Of course, since C lacks access specifiers you can't enforce that no-one peeks inside a struct FILE, but only a masochist would do so.)
If necessary, polymorphic behaviour can be had in C using tables of function pointers. Yes, the syntax is ugly but the effect is the same as virtual functions:
struct IAnimal {
int (*eat)(int food);
int (*sleep)(int secs);
};
/* "Subclass"/"implement" IAnimal, relying on C's guaranteed equivalence
* of memory layouts */
struct Cat {
struct IAnimal _base;
int (*meow)(void);
};
int cat_eat(int food) { ... }
int cat_sleep(int secs) { ... }
int cat_meow(void) { ... }
/* "Constructor" */
struct Cat* CreateACat(void) {
struct Cat* x = (struct Cat*) malloc(sizeof (struct Cat));
x->_base.eat = cat_eat;
x->_base.sleep = cat_sleep;
x->meow = cat_meow;
return x;
}
struct IAnimal* pa = CreateACat();
pa->eat(42); /* Calls cat_eat() */
((struct Cat*) pa)->meow(); /* "Downcast" */
All good answers.
I would only add "minimize data structure". This might even be easier in C, because if C++ is "C with classes", OOP is trying to encourage you to take every noun / verb in your head and turn it into a class / method. That can be very wasteful.
For example, suppose you have an array of temperature readings at points in time, and you want to display them as a line-chart in Windows. Windows has a PAINT message, and when you receive it, you can loop through the array doing LineTo functions, scaling the data as you go to convert it to pixel coordinates.
What I have seen entirely too many times is, since the chart consists of points and lines, people will build up a data structure consisting of point objects and line objects, each capable of DrawMyself, and then make that persistent, on the theory that that is somehow "more efficient", or that they might, just maybe, have to be able to mouse over parts of the chart and display the data numerically, so they build methods into the objects to deal with that, and that, of course, involves creating and deleting even more objects.
So you end up with a huge amount of code that is oh-so-readable and merely spends 90% of it's time managing objects.
All of this gets done in the name of "good programming practice" and "efficiency".
At least in C the simple, efficient way will be more obvious, and the temptation to build pyramids less strong.
The GNU coding standards have evolved over a couple of decades. It'd be a good idea to read them, even if you don't follow them to the letter. Thinking about the points raised in them gives you a firmer basis on how to structure your own code.
If you know how to structure your code in Java or C++, then you can follow the same principles with C code. The only difference is that you don't have the compiler at your side and you need to do everything extra carefully manually.
Since there are no packages and classes, you need to start by carefully designing your modules. The most common approach is to create a separate source folder for each module. You need to rely on naming conventions for differentiating code between different modules. For example prefix all functions with the name of the module.
You can't have classes with C, but you can easily implement "Abstract Data Types". You create a .C and .H file for every abstract data type. If you prefer you can have two header files, one public and one private. The idea is that all structures, constants and functions that need to be exported go to the public header file.
Your tools are also very important. A useful tool for C is lint, which can help you find bad smells in your code. Another tool you can use is Doxygen, which can help you generate documentation.
Encapsulation is always key to a successful development, regardless of the development language.
A trick I've used to help encapsulate "private" methods in C is to not include their prototypes in the ".h" file.
I'd suggets you to check out the code of any popular open source C project, like... hmm... Linux kernel, or Git; and see how they organize it.
The number rule for complex application: it should be easy to read.
To make complex application simplier, I employ Divide and conquer.
I would suggest reading a C/C++ textbook as a first step. For example, C Primer Plus is a good reference. Looking through the examples would give you and idea on how to map your java OO to a more procedural language like C.

Resources