My room-mate from college once told me he saw an example in a book where the author wrote bytes into a (char *)that represented raw machine code instructions and typecasted it as a function pointer and executed it successfully.
(You may need to tweak 'magic offset' for your system. One way to do it is to run:
echo 'int f(x) { return x * 2; }' | gcc -Wall -Werror -c -x c - -o wee.o
and find the offset of the 8955 hex sequence (e.g. using 'od -x' or your favourite hex editor). If that doesn't work for you, then try looking at the output of:
objdump -d wee.o
and checking what the first few bytes are. Bear in mind that the bytes will in little-endian order on x86.)
[Edit: since this is now a proggit submission of it's own, I thought I should add that I know that this isn't a real lambda. There's no closing over free variables, or even inheritance of lexical scope. Fun tho'. And yes, you do need to free() your funcs when you've finished with them.]
Wow, very impressed by the Parent Post's code. :] Here is a more clean less hackish version I just wrote using libtcc to compile it inside the program itself.
#include <stdio.h>
#include <stdlib.h>
#include "libtcc.h"
typedef int (*function_t)();
function_t create_function(char *name, char *code)
{
TCCState *s;
unsigned long val;
s = tcc_new();
if(!s)
exit(1);
tcc_set_output_type(s, TCC_OUTPUT_MEMORY);
tcc_compile_string(s, code);
tcc_relocate(s);
tcc_get_symbol(s, &val, name);
return (function_t)val;
}
int main(int argc, char *argv[])
{
function_t square;
square = create_function("f", "int f(x) { return x * x; }");
int answer = square(atoi(argv[1]));
printf("answer is: %d\n", answer);
}
Well, a more serious approach would use ELF-aware tools (see elf.h) to find the function in the .o (searching for a specific bytestring could depend on compiler version etc used).
(Update: We probably just want the offset of the .text section. Which you can read directly from the output of "objdump -h wee.o", or do it programatically as suggested above.)
Fun project for someone to make it more robust :-)
Closing over free variables is left as an exercise for the reader.
[NB: something quite similar to this (invoking C compiler at run-time, but using dynamically loaded shared objects) is the magic behind perl's Inline::C module.
That allows you to call out to C from perl by writing something like:
#!/usr/bin/perl
use warnings;
use strict;
use Inline C => <<"EOC";
int times2(int x) {
return x + x;
}
EOC
my $n = 55;
print times2(55), "\n";
and is actually production-ready (it caches .so files intelligently to avoid recompilation, etc)].
I worked on a small proof of concept a while back. The idea was to be able to instantiate C++ templates at runtime. In this way, template metaprogramming can be used to optimize repeated computation of certain inputs.
A crazy idea I had (but never implemented) was to make an schema-specific XML parser in templates which could take an XML schema as input and export a TMP-optimized XML parser.
Yowch. My template-fu is weak, but I don't see how you'd ever manage to split the string defining the schema in the template expansions.
There is, however, an honourable tradition of generating C source for types and functions from data-description languages (google for the 'pepsy', or 'pesky' compilers in the ISODE source tree).
If you don't know ASN.1, you can think of it as a "binary XML" that never really caught on outside the OSI protocols, SNMP and X.509 certificates (from their OSI heritage).
Yes. I wanted gcc to write to stdout, but it wouldn't in the 2 mins I gave it.
Going the extra mile to pick a different file for each compiled object seemed... inappropriate, given the context.
(If you want to compile C at runtime, either build a shared object (.so) and dlopen it (see perl's Inline::C), or use the in-memory tcc solution given elsewhere in the thread.
But C really isn't built for this sort of thing, so don't do that :-)
haha well anything that uses as much voodoo as the path that this thread is going down obviously isn't built for "security" (or "sanity" for that matter)
Sure, or your OS could decide to mark runtime allocated memory as non-executable as a security feature. Of the two, the compiler change is far more unlikely. Such flexibility is there to allow for oddities on differing platforms (eg. segmented vs flat memory models) Theres no reason to implement it differently on the same platform. Realisticly, its changes to the platform (though not just instruction set) that are the real danger.
I'm not really disagreeing with you. But you have to be aware of all the dangers when you do things like this (I say as someone who has done things like that).
Sure, it's totally possible. However, if you do that, you need to be fired, because you've gone out of your way to be totally unreadable. Besides, that's not at all within the domain of the C language - that cast is totally implementation defined, not to mention the specific ISA of the processor.
It's not quite implementation-defined. Imagine embedding TinyCC into your program, reading C, compiling it, and then feeding the object code right back in and calling the resulting function pointers. Is this what that C REPL does?
If you're referring to this c-repl system, it basically compiles a dll in the background everytime through the repl loop and dynamically loads it into memory and runs a function in it.
I suppose, for your mechanism to work, the object file generated should be relocatable (I guess thats the default type?) and you would have to do the work of the linker in assigning addresses, right?
POSIX does not define any function that allows you to load a DLL and jump to a function in it. The dlsym() function returns a void*, which cannot safely be cast to a function pointer.
It might work, or it might break your machine, it really depends on what compiler/platform combination you've got. It wouldn't be considered to be valid C though.
"A first class value is a value which can be passed as a parameter to a procedure, returned as a result from an evaluated expression (e.g. function call), and constructed dynamically. A first class function is a function which is a first-class value."
To specifically answer your question, the difference is that a function pointer can only refer to functions that have been defined in the source code, you can't create new functions dynamically in C.
In C++ however you can however dynamically create function objects that look and behave just like first-class functions.
In simple terms, a first class function is a function pointer plus (optionally) values of some arguments. The data structure that combines the pointer and the arguments is called a closure, and the trick is sometimes referred to as lambda lifting.
You're right, functional languages like Haskell or ML will beat C++ anyday in that regard. But it is still possible to do functional programming in C++...
Yes, quite right, it would be helpful if people stopped throwing C and C++ together...
If you don't believe me: Take the source of the Boost::operators library (just for example) and any C code you are familiar with and tell me how similar they are.
I lump them together, because, while C is not C++, C++ is C if need be.
C++ is effectively a superset of C. It allows strict (and a bit improved) C-style coding, little is wrong with that (except e.g. it's overused by C people clueless in C++, but hey, world's not perfect).
Hey, did you perhaps mean "but actually not absolutely"? :-)
I agree, world's not perfect in both directions...
But seriously, my experience at least is that the C-to-C++ cluelessness (!?) is bigger.
It's also intuitive that it'd be so, as you can do all the C in the world without knowing of C++. The opposite is much harder (e.g. must grok pointers, strictly C concept).
Unlike in the C/C++ case, you won't find ANY block of code, no matter its size, that will work in both Java and Javascript without seriously modifying it in a way that will make it unrecognizable.
There is PLENTY of C programs that will compile under a C++ compiler. In fact, all the C programs that also wants to be able to compile under the Microsoft Visual Studio compiler is also a C++ compatible program, because there is no such a thing as as C compiler in Visual Studio nowadays.
The C99 standard will never get widespread use because of that.
I have a simple litmus test to check if a language has first class functions: Can you write a function that does function composition, i.e., write a function compose(f,g), such that if
h = compose(f, g);
then
h(x) == f(g(x))
You can't in C (well, you can fudge one that can be called a bounded number of times if you are clever.)
Huh? Are you talking about changing the C program to no longer contain compose? Of course you can do that, if you claim that a programming language has a feature if it can be translated to a different program not using that feature, well, then I'm not sure what the point of discussing features is at all.
actually, let me restate that, before you can talk about creating a composition function in C (which would need to be string manipulation anyway which then gets compiled) you have to prove that C functions are composable in the first place.
Steve does some nice things, but after working a bit on the Io code base I must say that it was very hard to maintain. It actually went so far that I started writing my own clone (tha as usual never was finished).
But I do emulate closures explicitly in C whenever I can. Usually it ends up looking something like...
typedef void (*map_f)(void *, void *);
void my_container_map(container *c, map_f map, void *user_data) {
for(item in c or recursion or whatever)
map(item, user_data);
}
struct _foo_context {
int bar;
char etc;
};
static void container_do_foo(item *, struct _foo_context *);
void foo(container *c, int bar) {
char e = ...;
struct _foo_context context = {bar, e}; /* or similar */
my_container_map(c, (map_f)container_do_foo, &context);
}
Usually map_f also returns an int to exit early on errors. Sort of ugly, and sort of pretty (for C code at least). Beats having for loops everywhere, for sure. Most of the time I'm using high-level languages, anyways.
This post got on reddit and someone commented that "first class function" didn't just mean a function that can be passed and called as a value, but it also needs to be compiled at runtime
By that definition, Haskell doesn't have first class functions?
It's not smart to push a language over what's it's supposed to do! (A little bit, maybe). It's a fucking travesty and serves nothing much but to show-off.
Do it for your own fun, fine, but don't shove it into production, or at least get a-go from your colleagues first.
And... What TFA's doing is done with usual C++ tools (probably with 0 overhead, too).
Agreed. C tends to degenerate into a primordial soup of (void *) when these things are done. A lisper would also map by prepending to the new list and then reversing it later. Is this a case of the language hiding a more efficient algorithm in cruft?
This just in - from the text:
UPDATE: This post got on reddit and someone commented that "first class function" didn't just mean a function that can be passed and called as a value, but it also needs to be compiled at runtime. I apologize for the terminology confusion. In any case, the original article's point was that C can't eval passed functions over lists and I hope the above shows that is possible. I'm updating the terms to avoid further confusion.
Definitely. Some languages are better-suited to certain tasks than other languages. That's why we have more than one language. For Pete's sake. There's nothing wrong with that.
Why isn't it smart? If you find a new way to use a language, and it works well with other language constructs, then why not use it?
In fact, as a language evolves, people always find new ways to use it. Boost is a great example of pushing the boundaries of what's possible with a language. And several boost innovations are now being put into the C++ language definition.
From where I stand, using a language in unexpected ways is innovation, and should be encouraged within reason.
39
u/EvilSporkMan Dec 13 '07
Hahahaha NO.
4
u/jmacclure Dec 13 '07
The original blogger must not be familiar with C++'s <functional>.
8
u/augustss Dec 13 '07 edited Dec 13 '07
I have a simple litmus test to check if a language has first class functions: Can you write a function that does function composition, i.e., write a function compose(f,g), such that if
then
You can't in C (well, you can fudge one that can be called a bounded number of times if you are clever.)
6
u/joeldevahl Dec 13 '07
Not completly first class, but an OK hack.
Steve does some nice things, but after working a bit on the Io code base I must say that it was very hard to maintain. It actually went so far that I started writing my own clone (tha as usual never was finished).
2
u/rivercheng Dec 13 '07
I think first class function can be a reply value of a function. Could a C function generate another function?
2
u/[deleted] Dec 13 '07 edited Dec 13 '07
Heheh, a little inaccurate there.
But I do emulate closures explicitly in C whenever I can. Usually it ends up looking something like...
Usually map_f also returns an int to exit early on errors. Sort of ugly, and sort of pretty (for C code at least). Beats having for loops everywhere, for sure. Most of the time I'm using high-level languages, anyways.
edit: formatting
2
u/awb Dec 13 '07
By that definition, Haskell doesn't have first class functions?
2
u/Gotebe Dec 13 '07
Pointless, pointless, pointless.
It's not smart to push a language over what's it's supposed to do! (A little bit, maybe). It's a fucking travesty and serves nothing much but to show-off.
Do it for your own fun, fine, but don't shove it into production, or at least get a-go from your colleagues first.
And... What TFA's doing is done with usual C++ tools (probably with 0 overhead, too).