Storing address of mpz_t and passing the pointer around - c

From what I understand, mpz_t are nothing but a single-item array.
According to gmp.h:
{
short int _mp_alloc; /* Number of *limbs* allocated and pointed
to by the D field. */
short int _mp_size; /* abs(SIZE) is the number of limbs
the last field points to. If SIZE
is negative this is a negative
number. */
mp_limb_t *_mp_d; /* Pointer to the limbs. */
} __mpz_struct;
typedef __mpz_struct mpz_t[1];
That means that, given the way C handles arrays, mpz_t is effectively a pointer itself (to the first element of the one-element array).
Now, let's say I create a new mpz_t, within a function, "box" the pointer in an unsigned long long and return, then... chaos. (Since, I guess, the pointer is no longer valid?)
The only way I could in theory make it work is by moving the mpz_t declaration outside the function body (basically, make it a global)
Any other - more sensible - ideas?
Minimal example:
typedef uint64_t Value;
#define addWillOverflow(x,y,z) __builtin_sadd_overflow(x,y,z)
#define BITFIELD 56
#define MASK(x) ((Value)(x) << BITFIELD)
#define UNMASK 0x00FFFFFFFFFFFFFF
#define toI(v) ( (Value)(v & 0xFFFFFFFFu) | MASK(IV) )
#define toG(v) ( (Value)(v) | MASK(GV) )
#define GG(v) ( (v & UNMASK) )
Value addNumbers(int a, int b) {
Int32 res;
if (addWillOverflow(a,b,&res)) {
printf("overflow\n");
mpz_t ret;
mpz_init_set_si(ret,a);
mpz_add_ui(ret,ret,b);
return toG(ret);
}
else {
printf("normal addition\n");
return toI(res);
}
}
int main(int argc, char** argv) {
printf("3 + 5 = ");
printLnValue(addNumbers(1,2));
printf("2b + 2b = ");
Value a = addNumbers(2000000000,2000000000);
printLnValue(a);
printf("pointer: %p\n",GG(a));
Value b = addNumbers(2100000000,2011111111);
printLnValue(b);
printf("pointer: %p\n",GG(b));
}
Output:
3 + 5 = normal addition
3
2b + 2b = overflow
4000000000
pointer: 0x7ffee5b95630
overflow
4111111111
pointer: 0x7ffee5b95630
As you can see, the returned pointer is... the same. Although I would expect a different one.
UPDATE no 2
I'm currently thinking of doing it like this: (I'll see how it goes and then post it as a solution myself)
mpz_t* ret = malloc(sizeof(mpz_t));
mpz_init_set_si(*ret,a);
mpz_add_ui(*ret,*ret,b);
return toG(ret);

Related

C casting return values of structures

On an old C compiler that only passes structures by pointers I fortunately have a structure that is 4 bytes long. Which is the size of a long (not int) on this system.
The code I'm porting (awk V7 or 32V) has many functions that return this structure by value.
I'm trying to find a way to cast the structure a long and visa versa and while I have managed this for variables the cast fails with the return value of a function. I would be forced to use a temp long and then cast that. This means more than a simple define to solve my issue and means avoidable recoding.
Is there a way I can do this with just defines?
I have some sample code here that I'm playing around with. Sample code from different system has long of 64 bits so using int32 as long.
#include <stdio.h>
typedef struct _obj { char a; char b; short c; } Obj;
#define OBJ2INT *(int32*)&
#define INT2OBJ *(Obj*)&
/* Obj */ int32 newObj(a, b, c) /* was returing Obj */
char a; char b; int c;
{
Obj newobj;
newobj.a = a;
newobj.b = b;
newobj.c = c;
return OBJ2INT newobj;
}
int main(argc, argv)
int argc; char *argv[];
{
Obj a, b;
int32 t;
t = newObj('a', '1', 1));
a = INT2OBJ t; /* this works but require recoding with a temp variable */
b = INT2OBJ newObj('b', '2', 2); /* this is not allowed. even though the value is on the stack there is no address for return value */
printf("a = %c %c %d\n", a.a, a.b, a.c);
printf("b = %c %c %d\n", b.a, b.b, b.c);
}
I was missing the whole point. K & R C cannot assign or pass structures/unions.
So converting the int32 to a structure and assigning to another structure is never going to work. Can't assign structures! So the structure must always be converted to an int32. because int32 can be assigned and passed. The solution was to change this :
b = INT2OBJ newObj('b', '2', 2); /* this is not allowed. even though the value is on the stack there is no address for return value */
to this :
OBJ2INT b = newObj('b', '2', 2);
INT2OBJ is never required. What was required was moving the INT2OBJ from the right to a OBJ2INT on the left of the assignment!

Point to a function with an already - provided arguments [duplicate]

I would like this to work, but it does not:
#include <stdio.h>
typedef struct closure_s {
void (*incrementer) ();
void (*emitter) ();
} closure;
closure emit(int in) {
void incrementer() {
in++;
}
void emitter() {
printf("%d\n", in);
}
return (closure) {
incrementer,
emitter
};
}
main() {
closure test[] = {
emit(10),
emit(20)
};
test[0] . incrementer();
test[1] . incrementer();
test[0] . emitter();
test[1] . emitter();
}
It actually does compile and does work for 1 instance ... but the second one fails. Any idea how to get closures in C?
It would be truly awesome!
Using FFCALL,
#include <callback.h>
#include <stdio.h>
static void incrementer_(int *in) {
++*in;
}
static void emitter_(int *in) {
printf("%d\n", *in);
}
int main() {
int in1 = 10, in2 = 20;
int (*incrementer1)() = alloc_callback(&incrementer_, &in1);
int (*emitter1)() = alloc_callback(&emitter_, &in1);
int (*incrementer2)() = alloc_callback(&incrementer_, &in2);
int (*emitter2)() = alloc_callback(&emitter_, &in2);
incrementer1();
incrementer2();
emitter1();
emitter2();
free_callback(incrementer1);
free_callback(incrementer2);
free_callback(emitter1);
free_callback(emitter2);
}
But usually in C you end up passing extra arguments around to fake closures.
Apple has a non-standard extension to C called blocks, which do work much like closures.
The ANSI C has not a support for closure, as well as nested functions. Workaround for it is usage simple "struct".
Simple example closure for sum two numbers.
// Structure for keep pointer for function and first parameter
typedef struct _closure{
int x;
char* (*call)(struct _closure *str, int y);
} closure;
// An function return a result call a closure as string
char *
sumY(closure *_closure, int y) {
char *msg = calloc(20, sizeof(char));
int sum = _closure->x + y;
sprintf(msg, "%d + %d = %d", _closure->x, y, sum);
return msg;
}
// An function return a closure for sum two numbers
closure *
sumX(int x) {
closure *func = (closure*)malloc(sizeof(closure));
func->x = x;
func->call = sumY;
return func;
}
Usage:
int main (int argv, char **argc)
{
closure *sumBy10 = sumX(10);
puts(sumBy10->call(sumBy10, 1));
puts(sumBy10->call(sumBy10, 3));
puts(sumBy10->call(sumBy10, 2));
puts(sumBy10->call(sumBy10, 4));
puts(sumBy10->call(sumBy10, 5));
}
Result:
10 + 1 = 11
10 + 3 = 13
10 + 2 = 12
10 + 4 = 14
10 + 5 = 15
On C++11 it will be achived by use lambda expression.
#include <iostream>
int main (int argv, char **argc)
{
int x = 10;
auto sumBy10 = [x] (int y) {
std::cout << x << " + " << y << " = " << x + y << std::endl;
};
sumBy10(1);
sumBy10(2);
sumBy10(3);
sumBy10(4);
sumBy10(5);
}
A result, after compilation with a flag -std=c++11.
10 + 1 = 11
10 + 2 = 12
10 + 3 = 13
10 + 4 = 14
10 + 5 = 15
A Working Definition of a Closure with a JavaScript Example
A closure is a kind of object that contains a pointer or reference of some kind to a function to be executed along with the an instance of the data needed by the function.
An example in JavaScript from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures is
function makeAdder(x) {
return function(y) { // create the adder function and return it along with
return x + y; // the captured data needed to generate its return value
};
}
which could then be used like:
var add5 = makeAdder(5); // create an adder function which adds 5 to its argument
console.log(add5(2)); // displays a value of 2 + 5 or 7
Some of the Obstacles to Overcome with C
The C programming language is a statically typed language, unlike JavaScript, nor does it have garbage collection, and some other features that make it easy to do closures in JavaScript or other languages with intrinsic support for closures.
One large obstacle for closures in Standard C is the lack of language support for the kind of construct in the JavaScript example in which the closure includes not only the function but also a copy of data that is captured when the closure is created, a way of saving state which can then be used when the closure is executed along with any additional arguments provided at the time the closure function is invoked.
However C does have some basic building blocks which can provide the tools for creating a kind of closure. Some of the difficulties are (1) memory management is the duty of the programmer, no garbage collection, (2) functions and data are separated, no classes or class type mechanics, (3) statically typed so no run time discovery of data types or data sizes, and (4) poor language facilities for capturing state data at the time the closure is created.
One thing that makes something of a closure facility possible with C is the void * pointer and using unsigned char as a kind of general purpose memory type which is then transformed into other types through casting.
An update with new approach
My original posted answer seems to have been helpful enough that people have upvoted it however it had a constraint or two that I didn't like.
Getting a notification of a recent upvote, I took a look at some of the other posted answers and realized that I could provide a second approach that would overcome the problem that bothered me.
A new approach that removes a problem of the original approach
The original approach required function arguments to be passed on the stack. This new approach eliminates that requirement. It also seems much cleaner. I'm keeping the original approach below.
The new approach uses a single struct, ClosureStruct, along with two functions to build the closure, makeClosure() and pushClosureArg().
This new approach also uses the variable argument functionality of stdarg.h to process the captured arguments in the closure data.
Using the following in a C source code file requires the following includes:
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <stdarg.h>
typedef struct {
void (*p)(); // pointer to the function of this closure
size_t sargs; // size of the memory area allocated for closure data
size_t cargs; // current memory area in use for closure data
unsigned char * args; // pointer to the allocated closure data area
} ClosureStruct;
void * makeClosure(void (*p)(), size_t sargs)
{
// allocate the space for the closure management data and the closure data itself.
// we do this with a single call to calloc() so that we have only one pointer to
// manage.
ClosureStruct* cp = calloc(1, sizeof(ClosureStruct) + sargs);
if (cp) {
cp->p = p; // save a pointer to the function
cp->sargs = sargs; // save the total size of the memory allocated for closure data
cp->cargs = 0; // initialize the amount of memory used
cp->args = (unsigned char *)(cp + 1); // closure data is after closure management block
}
return cp;
}
void * pushClosureArg(void* cp, size_t sarg, void* arg)
{
if (cp) {
ClosureStruct* p = cp;
if (p->cargs + sarg <= p->sargs) {
// there is room in the closure area for this argument so make a copy
// of the argument and remember our new end of memory.
memcpy(p->args + p->cargs, arg, sarg);
p->cargs += sarg;
}
}
return cp;
}
This code is then used similar to the following:
// example functions that we will use with closures
// funcadd() is a function that accepts a closure with two int arguments
// along with three additional int arguments.
// it is similar to the following function declaration:
// void funcadd(int x1, int x2, int a, int b, int c);
//
void funcadd(ClosureStruct* cp, int a, int b, int c)
{
// using the variable argument functionality we will set our
// variable argument list address to the closure argument memory area
// and then start pulling off the arguments that are provided by the closure.
va_list jj;
va_start(jj, cp->args); // get the address of the first argument
int x1 = va_arg(jj, int); // get the first argument of the closure
int x2 = va_arg(jj, int);
printf("funcadd() = %d\n", a + b + c + x1 + x2);
}
int zFunc(ClosureStruct* cp, int j, int k)
{
va_list jj;
va_start(jj, cp->args); // get the address of the first argument
int i = va_arg(jj, int);
printf("zFunc() i = %d, j = %d, k = %d\n", i, j, k);
return i + j + k;
}
typedef struct { char xx[24]; } thing1;
int z2func( ClosureStruct* cp, int i)
{
va_list jj;
va_start(jj, cp->args); // get the address of the first argument
thing1 a = va_arg(jj, thing1);
printf("z2func() i = %d, %s\n", i, a.xx);
return 0;
}
int mainxx(void)
{
ClosureStruct* p;
int x;
thing1 xpxp = { "1234567890123" };
p = makeClosure(funcadd, 256);
x = 4; pushClosureArg(p, sizeof(int), &x);
x = 10; pushClosureArg(p, sizeof(int), &x);
p->p(p, 1, 2, 3);
free(p);
p = makeClosure(z2func, sizeof(thing1));
pushClosureArg(p, sizeof(thing1), &xpxp);
p->p(p, 45);
free(p);
p = makeClosure(zFunc, sizeof(int));
x = 5; pushClosureArg(p, sizeof(int), &x);
p->p(p, 12, 7);
return 0;
}
The output from the above usage is:
funcadd() = 20
z2func() i = 45, 1234567890123
zFunc() i = 5, j = 12, k = 7
However there is an issue with the above implementation, you have no way of getting the return value of a function that returns a value. In other words, the function zFunc() used in a closure above returns an int value which is ignored. If you try to capture the return value with something like int k = pint->p(pint, 12, 7); you will get an error message because the function pointer argument of ClosureStruct is void (*p)(); rather than int (*p)();.
To work around this restraint, we will add two C Preprocessor macros to help us create individual versions of the ClosureStruct struct that specify a function return type other than void.
#define NAME_CLOSURE(t) ClosureStruct_ ## t
#define DEF_CLOSURE(t) \
typedef struct { \
t (*p)(); \
size_t sargs; \
size_t cargs; \
unsigned char* args; \
} NAME_CLOSURE(t);
We then redefine the two functions, zFunc() and z2func(), as follows using the macros.
DEF_CLOSURE(int) // define closure struct that returns an int
int zFunc(NAME_CLOSURE(int)* cp, int j, int k)
{
va_list jj;
va_start(jj, cp->args); // get the address of the first argument
int i = va_arg(jj, int);
printf("zFunc() i = %d, j = %d, k = %d\n", i, j, k);
return i + j + k;
}
typedef struct { char xx[24]; } thing1;
int z2func( NAME_CLOSURE(int) * cp, int i)
{
va_list jj;
va_start(jj, cp->args); // get the address of the first argument
thing1 a = va_arg(jj, thing1);
printf("z2func() i = %d, %s\n", i, a.xx);
return 0;
}
And we use this as follows:
int mainxx(void)
{
ClosureStruct* p;
NAME_CLOSURE(int) *pint;
int x;
thing1 xpxp = { "1234567890123" };
p = makeClosure(funcadd, 256);
x = 4; pushClosureArg(p, sizeof(int), &x);
x = 10; pushClosureArg(p, sizeof(int), &x);
p->p(p, 1, 2, 3);
free(p);
pint = makeClosure(z2func, sizeof(thing1));
pushClosureArg(pint, sizeof(thing1), &xpxp);
int k = pint->p(pint, 45);
free(pint);
pint = makeClosure(zFunc, sizeof(int));
x = 5; pushClosureArg(pint, sizeof(int), &x);
k = pint->p(pint, 12, 7);
return 0;
}
First Implementation With Standard C and a Bit of Stretching Here and There
NOTE: The following example depends on a stack based argument passing convention as is used with most x86 32 bit compilers. Most compilers also allow for a calling convention to be specified other than stack based argument passing such as the __fastcall modifier of Visual Studio. The default for x64 and 64 bit Visual Studio is to use the __fastcall convention by default so that function arguments are passed in registers and not on the stack. See Overview of x64 Calling Conventions in the Microsoft MSDN as well as How to set function arguments in assembly during runtime in a 64bit application on Windows? as well as the various answers and comments in How are variable arguments implemented in gcc? .
One thing that we can do is to solve this problem of providing some kind of closure facility for C is to simplify the problem. Better to provide an 80% solution that is useful for a majority of applications than no solution at all.
One such simplification is to only support functions that do not return a value, in other words functions declared as void func_name(). We are also going to give up compile time type checking of the function argument list since this approach builds the function argument list at run time. Neither one of these things that we are giving up are trivial so the question is whether the value of this approach to closures in C outweighs what we are giving up.
First of all lets define our closure data area. The closure data area represents the memory area we are going to use to contain the information we need for a closure. The minimum amount of data I can think of is a pointer to the function to execute and a copy of the data to be provided to the function as arguments.
In this case we are going to provide any captured state data needed by the function as an argument to the function.
We also want to have some basic safe guards in place so that we will fail reasonably safely. Unfortunately the safety rails are a bit weak with some of the work arounds we are using to implement a form of closures.
The Source Code
The following source code was developed using Visual Studio 2017 Community Edition in a .c C source file.
The data area is a struct that contains some management data, a pointer to the function, and an open ended data area.
typedef struct {
size_t nBytes; // current number of bytes of data
size_t nSize; // maximum size of the data area
void(*pf)(); // pointer to the function to invoke
unsigned char args[1]; // beginning of the data area for function arguments
} ClosureStruct;
Next we create a function that will initialize a closure data area.
ClosureStruct * beginClosure(void(*pf)(), int nSize, void *pArea)
{
ClosureStruct *p = pArea;
if (p) {
p->nBytes = 0; // number of bytes of the data area in use
p->nSize = nSize - sizeof(ClosureStruct); // max size of the data area
p->pf = pf; // pointer to the function to invoke
}
return p;
}
This function is designed to accept a pointer to a data area which gives flexibility as to how the user of the function wants to manage memory. They can either use some memory on the stack or static memory or they can use heap memory via the malloc() function.
unsigned char closure_area[512];
ClosureStruct *p = beginClosure (xFunc, 512, closure_area);
or
ClosureStruct *p = beginClosure (xFunc, 512, malloc(512));
// do things with the closure
free (p); // free the malloced memory.
Next we provide a function that allows us to add data and arguments to our closure. The purpose of this function is to build up the closure data so that when closure function is invoked, the closure function will be provided any data it needs to do its job.
ClosureStruct * pushDataClosure(ClosureStruct *p, size_t size, ...)
{
if (p && p->nBytes + size < p->nSize) {
va_list jj;
va_start(jj, size); // get the address of the first argument
memcpy(p->args + p->nBytes, jj, size); // copy the specified size to the closure memory area.
p->nBytes += size; // keep up with how many total bytes we have copied
va_end(jj);
}
return p;
}
And to make this a bit simpler to use lets provide a wrapping macro which is generally handy but does have limitations since it is C Processor text manipulation.
#define PUSHDATA(cs,d) pushDataClosure((cs),sizeof(d),(d))
so we could then use something like the following source code:
unsigned char closurearea[256];
int iValue = 34;
ClosureStruct *dd = PUSHDATA(beginClosure(z2func, 256, closurearea), iValue);
dd = PUSHDATA(dd, 68);
execClosure(dd);
Invoking the Closure: The execClosure() Function
The last piece to this is the execClosure() function to execute the closure function with its data. What we are doing in this function is to copy the argument list supplied in the closure data structure onto the stack as we invoke the function.
What we do is cast the args area of the closure data to a pointer to a struct containing an unsigned char array and then dereference the pointer so that the C compiler will put a copy of the arguments onto the stack before it calls the function in the closure.
To make it easier to create the execClosure() function, we will create a macro that makes it easy to create the various sizes of structs we need.
// helper macro to reduce type and reduce chance of typing errors.
#define CLOSEURESIZE(p,n) if ((p)->nBytes < (n)) { \
struct {\
unsigned char x[n];\
} *px = (void *)p->args;\
p->pf(*px);\
}
Then we use this macro to create a series of tests to determine how to call the closure function. The sizes chosen here may need tweaking for particular applications. These sizes are arbitrary and since the closure data will rarely be of the same size, this is not efficiently using stack space. And there is the possibility that there may be more closure data than we have allowed for.
// execute a closure by calling the function through the function pointer
// provided along with the created list of arguments.
ClosureStruct * execClosure(ClosureStruct *p)
{
if (p) {
// the following structs are used to allocate a specified size of
// memory on the stack which is then filled with a copy of the
// function argument list provided in the closure data.
CLOSEURESIZE(p,64)
else CLOSEURESIZE(p, 128)
else CLOSEURESIZE(p, 256)
else CLOSEURESIZE(p, 512)
else CLOSEURESIZE(p, 1024)
else CLOSEURESIZE(p, 1536)
else CLOSEURESIZE(p, 2048)
}
return p;
}
We return the pointer to the closure in order to make it easily available.
An Example Using the Library Developed
We can use the above as follows. First a couple of example functions that don't really do much.
int zFunc(int i, int j, int k)
{
printf("zFunc i = %d, j = %d, k = %d\n", i, j, k);
return i + j + k;
}
typedef struct { char xx[24]; } thing1;
int z2func(thing1 a, int i)
{
printf("i = %d, %s\n", i, a.xx);
return 0;
}
Next we build our closures and execute them.
{
unsigned char closurearea[256];
thing1 xpxp = { "1234567890123" };
thing1 *ypyp = &xpxp;
int iValue = 45;
ClosureStruct *dd = PUSHDATA(beginClosure(z2func, 256, malloc(256)), xpxp);
free(execClosure(PUSHDATA(dd, iValue)));
dd = PUSHDATA(beginClosure(z2func, 256, closurearea), *ypyp);
dd = PUSHDATA(dd, 68);
execClosure(dd);
dd = PUSHDATA(beginClosure(zFunc, 256, closurearea), iValue);
dd = PUSHDATA(dd, 145);
dd = PUSHDATA(dd, 185);
execClosure(dd);
}
Which gives an output of
i = 45, 1234567890123
i = 68, 1234567890123
zFunc i = 45, j = 145, k = 185
Well What About Currying?
Next we could make a modification to our closure struct to allow us to do currying of functions.
typedef struct {
size_t nBytes; // current number of bytes of data
size_t nSize; // maximum size of the data area
size_t nCurry; // last saved nBytes for curry and additional arguments
void(*pf)(); // pointer to the function to invoke
unsigned char args[1]; // beginning of the data area for function arguments
} ClosureStruct;
with the supporting functions for currying and resetting of a curry point being
ClosureStruct *curryClosure(ClosureStruct *p)
{
p->nCurry = p->nBytes;
return p;
}
ClosureStruct *resetCurryClosure(ClosureStruct *p)
{
p->nBytes = p->nCurry;
return p;
}
The source code for testing this could be:
{
unsigned char closurearea[256];
thing1 xpxp = { "1234567890123" };
thing1 *ypyp = &xpxp;
int iValue = 45;
ClosureStruct *dd = PUSHDATA(beginClosure(z2func, 256, malloc(256)), xpxp);
free(execClosure(PUSHDATA(dd, iValue)));
dd = PUSHDATA(beginClosure(z2func, 256, closurearea), *ypyp);
dd = PUSHDATA(dd, 68);
execClosure(dd);
dd = PUSHDATA(beginClosure(zFunc, 256, closurearea), iValue);
dd = PUSHDATA(dd, 145);
dd = curryClosure(dd);
dd = resetCurryClosure(execClosure(PUSHDATA(dd, 185)));
dd = resetCurryClosure(execClosure(PUSHDATA(dd, 295)));
}
with the output of
i = 45, 1234567890123
i = 68, 1234567890123
zFunc i = 45, j = 145, k = 185
zFunc i = 45, j = 145, k = 295
GCC and clang have the blocks extension, which is essentially closures in C.
GCC supports inner functions, but not closures. C++0x will have closures. No version of C that I'm aware of, and certainly no standard version, provides that level of awesome.
Phoenix, which is part of Boost, provides closures in C++.
On this page you can find a description on how to do closures in C:
http://brodowsky.it-sky.net/2014/06/20/closures-in-c-and-scala/
The idea is that a struct is needed and that struct contains the function pointer, but gets provided to the function as first argument. Apart from the fact that it requires a lot of boiler plate code and the memory management is off course an issue, this works and provides the power and possibilities of other languages' closures.
You can achieve this with -fblocks flag, but it does not look so nice like in JS or TS:
#include <stdio.h>
#include <stdlib.h>
#include <Block.h>
#define NEW(T) ({ \
T* __ret = (T*)calloc(1, sizeof(T)); \
__ret; \
})
typedef struct data_t {
int value;
} data_t;
typedef struct object_t {
int (^get)(void);
void (^set)(int);
void (^free)(void);
} object_t;
object_t const* object_create(void) {
data_t* priv = NEW(data_t);
object_t* pub = NEW(object_t);
priv->value = 123;
pub->get = Block_copy(^{
return priv->value;
});
pub->set = Block_copy(^(int value){
priv->value = value;
});
pub->free = Block_copy(^{
free(priv);
free(pub);
});
return pub;
}
int main() {
object_t const* obj = object_create();
printf("before: %d\n", obj->get());
obj->set(321);
printf("after: %d\n", obj->get());
obj->free();
return 0;
}
clang main.c -o main.o -fblocks -fsanitize=address; ./main.o
before: 123
after: 321
The idiomatic way of doing it in is C is passing a function pointer and a void pointer to the context.
However, some time ago I came up with a different approach. Surprisingly, there is a family of builtin types in C that carries both a data and the code itself. Those are pointers to a function pointer.
The trick is use this single object to pass both the code by dereferencing a function pointer. And next passing the very same double function pointer as the context as a first argument. It looks a bit convoluted by actually it results in very flexible and readable machanism for closures.
See the code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// typedefing functions makes usually makes code more readable
typedef double double_fun_t(void*, double);
struct exponential {
// closure must be placed as the first member to allow safe casting
// between a pointer to `closure` and `struct exponential`
double_fun_t *closure;
double temperature;
};
double exponential(void *ctx_, double x) {
struct exponential *ctx = ctx_;
return exp(x / ctx->temperature);
}
// the "constructor" of the closure for exponential
double_fun_t **make_exponential(double temperature) {
struct exponential *e = malloc(sizeof *e);
e->closure = exponential;
e->temperature = temperature;
return &e->closure;
}
// now simple closure with no context, a pure x -> x*x mapping
double square(void *_unused, double x){
(void)_unused;
return x*x;
}
// use compound literal to transform a function to a closure
double_fun_t **square_closure = & (double_fun_t*) { square };
// the worker that process closures, note that `double_fun_t` is not used
// because `double(**)(void*,double)` is builtin type
double somme(double* liste, int length, double (**fun)(void*,double)){
double poids = 0;
for(int i=0;i<length;++i)
// calling a closure, note that `fun` is used for both obtaing
// the function pointer and for passing the context
poids = poids + (*fun)(fun, liste[i]);
return poids;
}
int main(void) {
double list[3] = { 1, 2, 3 };
printf("%g\n", somme(list, 3, square_closure));
// a dynamic closure
double_fun_t **exponential = make_exponential(42);
printf("%g\n", somme(list, 3, exponential));
free(exponential);
return 0;
}
The advantage of this approach is that the closure exports a pure interface for calling double->double functions. There is no need to introduce any boxing structures used by all clients of the closure. The only requirement is the "calling convention" which is very natural and does not require sharing any code.
Answer
#include <stdio.h>
#include <stdlib.h>
/*
File Conventions
----------------
alignment: similar statements only
int a = 10;
int* omg = {120, 5};
functions: dofunction(a, b, c);
macros: _do_macro(a, b, c);
variables: int dovariable=10;
*/
////Macros
#define _assert(got, expected, teardownmacro) \
do { \
if((got)!=(expected)) { \
fprintf(stderr, "line %i: ", __LINE__); \
fprintf(stderr, "%i != %i\n", (got), (expected)); \
teardownmacro; \
return EXIT_FAILURE; \
} \
} while(0);
////Internal Helpers
static void istarted() {
fprintf(stderr, "Start tests\n");
}
static void iended() {
fprintf(stderr, "End tests\n");
}
////Tests
int main(void)
{
///Environment
int localvar = 0;
int* localptr = NULL;
///Closures
#define _setup_test(mvar, msize) \
do { \
localptr=calloc((msize), sizeof(int)); \
localvar=(mvar); \
} while(0);
#define _teardown_test() \
do { \
free(localptr); \
localptr=NULL; \
} while(0);
///Tests
istarted();
_setup_test(10, 2);
_assert(localvar, 10, _teardown_test());
_teardown_test();
_setup_test(100, 5);
_assert(localvar, 100, _teardown_test());
_teardown_test();
iended();
return EXIT_SUCCESS;
}
Context
I was curious about how others accomplished this in C. I wasn't totally surprised when I didn't see this answer. Warning: This answer is not for beginners.
I live a lot more in the Unix style of thinking: lots of my personal programs and libraries are small and do one thing very well. Macros as "closures" are much safer in this context. I believe all the organization and specified conventions for readability is super important, so the code is readable by us later, and a macro looks like a macro and a function looks like a function. To clarify, not literally these personal conventions, just having some, that are specified and followed to distinguish different language constructs (macros and functions). We all should be doing that anyway.
Don't do afraid of macros. When it makes sense: use them. The advanced part is the when. My example is one example of the whens. They are ridiculously powerful and not that scary.
Rambling
I sometimes use a proper closure/lambda in other languages to execute a set of expressions over and over within a function. It's a little context aware private helper function. Regardless of its proper definition, that's something a closure can do. It helps me write less code. Another benefit of this is you don't need to reference a struct to know how to use it or understand what it's doing. The other answers do not have this benefit, and, if it wasn't obvious I hold readability very highly. I strive for simple legible solutions. This one time I wrote an iOS app and it was wonderful and as simple as I could get it. Then I wrote the same "app" in bash in like 5 lines of code and cursed.
Also embedded systems.

How can I check if a variable in a struct is not used in C?

Here is the code I have so far.
I am trying to be able to tell if a certain variable inside a struct is empty. I am going to be creating a struct with some variables being filled and some not and need to know which ones need me to do something and which ones don't.
#include <stdio.h>
#include <stdlib.h>
struct nums {
int a;
int b;
int c;
int d;
} typedef numbers;
int main() {
numbers bob;
bob.a = 69;
if (bob.b == NULL) {
printf("no number stored in b");
}
return 0;
}
but I just get the error
warning: comparison between pointer and integer
Any ideas?
What you are trying to do has not sense in C.
The only solution is to analyze your code and to proof, with a logical analysis, that certain variable is used (or not).
I'll give two ideas that can help you, anyway.
1. INITIALIZATION TO DUMMY VALUE
One could choose a value in the range of the type of the variable that we know that it has not a meaning among the values that our program handle.
For example, for the int type one could choose INT_MIN as such a dummy value.
It's the most negative value that the int type can hold.
In 32-bit 2's complement ints this value is -2147483648, which is probably your case.
[INT_MAX is defined in <limits.h>, so you have to #include it.]
#include <limits.h>
numbers bob = { INT_MIN, INT_MIN, INT_MIN, INT_MIN};
if (bob.b == INT_MIN) puts("Unused object.");
This method works, provided that you never have INT_MIN as a valid value in the rest of your program.
2. CHANGE YOUR APPROACH
Instead of using int, one could use a pointer to an int:
#include <stdio.h>
#include <stdlib.h>
typedef struct { int *a, *b, *c, *d; } pnumbers;
int main(void) {
pnumbers bob = { NULL, NULL, NULL, NULL };
int val = 32;
bob.a = &val;
bob.c = malloc(sizeof(int));
bob->c = 20;
if (bob.a != NULL) printf("%d\n", bob->a);
if (bob.b == NULL) puts("Unused member");
if (bob.c != NULL) printf("%d\n", bob->c);
}
Usually there is no way to tell if you have actually stored something in an int variable.
In your case, though, you could:
Initialize your struct: numbers bob = { 0 }; // <-- this makes a, b, c, d equal to zero
Then check if you have any number different than 0:
if(bob.b == 0){
printf("no non-zero number stored in b");
}

C Union definition

Within a struct I need some space where I can put in something. This space have to be able to collect all data types, so I want to define an union. The space is limited to n bytes (unsigned char).
How do I have to define my union, so that it can contain char, int, float and so on?
Have I to do it this way?
#define SIZE (128)
union {
unsigned char uchar[SIZE];
char schar[SIZE];
unsigned int uint[SIZE/sizeof(unsigned int)];
int sint[SIZE/sizeof(int)];
float flt[SIZE/sizeof(float)];
double dbl[SIZE/sizeof(double)];
}memory;
Or is there a possibility to define only the size of the unsigned char array and then to define size of the int array automatically? What does happen, if SIZE isn't divisible by 4?
EDIT: (related to the comments)
I want to build something like an timed event handler. That means, I have a struct containing an array of events. Each event has an execution time and a related function (stored as a pointer). When the timer counter of the event handler matches the event execution time, I call the related function. Within the function I will know, wich arguments are expected, so I don't need to save a tag value. The problem is, that the events are created within a funtion and because I don't want to make the events static (to save memory), I added some memory (ring buffer) to my event handler where all functions can put in some data. Each event will have a variable containing the pointer to the (first) data. The type of data are only the nativ data types, no own structs.
This is my current code:
startSystemClock() will be called at start up
executeSystemEvent() will be called by the interrupt service routine of timer 1 by setting sysEventHandler.execute=TRUE and a while(1)-loop checks this flag and then calls executeSystemEvent()
// typedefs requird for timed events
typedef union __attribute__ ((packed)){
int *i; // pointer, where data is stored
int value; // if there is a pointer assigned, value differs from zero
}systemEventData_u;
typedef union __attribute__ ((packed)){
int value; // if there is a pointer assigned, value differs from zero
void (*voidFct_noData)();
void (*voidFct_data)(systemEventData_u);
}systemEventFct_u;
typedef struct{
int time;
unsigned int id;
systemEventFct_u fct;
systemEventData_u data;
}systemEvent_t;
#define SYSTEM_EVENT_HANDLER_BUFFER_SIZE (10)
#define SYSTEM_EVENT_HANDLER_MEMORY_SIZE (10)
typedef struct{
unsigned int actualCnt;
unsigned int nextEventCnt;
unsigned char execute;
systemEvent_t events[SYSTEM_EVENT_HANDLER_BUFFER_SIZE];
systemEvent_t* write;
// create some persistent memory usable by all functions
int* memWrite;
union __attribute__ ((packed)){
unsigned char uchar[0];
char schar[0];
unsigned int uint[0];
int sint[SYSTEM_EVENT_HANDLER_MEMORY_SIZE];
float flt[0];
double dbl[0];
}memory;
}systemEventHandler_t;
void startSystemClock(){
// initialize event handler
sysEventHandler.actualCnt=0;
sysEventHandler.nextEventCnt=-1;
sysEventHandler.execute=FALSE;
sysEventHandler.write=sysEventHandler.events;
sysEventHandler.memWrite=sysEventHandler.memory.sint;
unsigned int i=SYSTEM_EVENT_HANDLER_BUFFER_SIZE;
systemEvent_t *ptr=sysEventHandler.events;
while(i--){
ptr->fct.value=0;
ptr->data.value=0;
ptr->time=0;
ptr++;
}
// initialize timer 1
TMR1 = 0x00;
T1CON = T3_OFF | T3_IDLE_CON | T3_GATE_OFF | T1_PS_1_8 | T1_SOURCE_INT;
IPC1SET = (INTERRUPT_PRIOR_TIMER1 << _IPC1_T1IP_POSITION) | (INTERRUPT_SUB_PRIOR_TIMER1 << _IPC1_T1IS_POSITION);
IFS0CLR = (1 << _IFS0_T1IF_POSITION);
IEC0SET = (1 << _IEC0_T1IE_POSITION);
PR1 = PR_TIMER1;
T1CONSET = (1 << _T1CON_ON_POSITION);
print_text("timer1 started\n\r");
}
void executeSystemEvent(){
asm("di");
int time=sysEventHandler.actualCnt;
asm("ei");
unsigned int i=SYSTEM_EVENT_HANDLER_BUFFER_SIZE;
unsigned int nextEventCnt=-1;
systemEvent_t *ptr=sysEventHandler.events;
while(i--){
// do not investigate, if there is no function pointer
// no function pointer means no event action
if(ptr->fct.value){
if(time>=ptr->time){
// execute function
if(ptr->data.value){
(*ptr->fct.voidFct_data)(ptr->data);
}else{
(*ptr->fct.voidFct_noData)();
}
ptr->fct.value=0;
}
}
ptr++;
}
// determine next event
// iterate again through whole queue to take added events into account also
i=SYSTEM_EVENT_HANDLER_BUFFER_SIZE;
ptr=sysEventHandler.events;
while(i--){
if(ptr->fct.value){
// get execution time to determine next one
if(ptr->time<nextEventCnt){
nextEventCnt=ptr->time;
}
}
ptr++;
}
asm("di");
sysEventHandler.nextEventCnt=nextEventCnt;
sysEventHandler.execute=FALSE;
asm("ei");
}
void addSystemEvent(systemEvent_t event){
// check, if this event will be the first event to execute
asm("di");
// get event execution time
event.time+=sysEventHandler.actualCnt;
// check, if it will be the next one to execute
if(sysEventHandler.nextEventCnt>event.time){
sysEventHandler.nextEventCnt=event.time;
}
asm("ei");
*sysEventHandler.write=event;
if(++sysEventHandler.write>=sysEventHandler.events+SYSTEM_EVENT_HANDLER_BUFFER_SIZE){
sysEventHandler.write=sysEventHandler.events;
}
}
int * storeSystemEventData(int data){
int *ptr=sysEventHandler.memWrite;
*ptr=data;
if(++sysEventHandler.memWrite>=sysEventHandler.memory.sint+SYSTEM_EVENT_HANDLER_MEMORY_SIZE){
sysEventHandler.memWrite=sysEventHandler.memory.sint;
}
return ptr;
}
To add an event, I write within any function:
systemEvent_t event;
event.fct.voidFct_data=&enablePinChangeInterrupt_wrapper;
event.data.i=storeSystemEventData((int)PUSHBUTTON_CN_BIT);
event.time=10;
addSystemEvent(event);
I know, that the storeSystemEventData-function isn't complete. But for my first purpose, I only need int, so it works.
You don't need to specify the array sizes except for the biggest. Just out-of-bounds access the other types.
#include "stdio.h"
union memory {
unsigned char uchar[128];
char schar[0];
unsigned int uint[0];
int sint[0];
float flt[0];
double dbl[0];
} ;
int main (void)
{
union memory my_mem;
my_mem.schar[5] = 'A';
my_mem.schar[6] = 'B';
my_mem.schar[7] = 'C';
my_mem.schar[8] = 'D';
printf ("%d\n", my_mem.uint[1]);
return 0;
}
C doesn't provide array bounds checking either way, so you're just out of luck if you try to access memory outside the memory object.
What does happen, if SIZE isn't divisible by 4?
I assume you ask the question about divisibility by 4 (as opposed by any other number) because it is a common sizeof(int). When SIZE is indivisible by any of the sizeofs, would end up with the largest array that fits fully inside the size, i.e. the number would be truncated. For example, setting SIZE to 13 when sizeof(int) is 4 would produce
int sint[3];
In other words, the size would be "rounded down" (truncated). If you prefer rounding up, use this expression:
unsigned int uint[(SIZE+sizeof(unsigned int)-1)/sizeof(unsigned int)];
Note, however, that the size of uint[] array may exceed the size of uchar.
is there a possibility to define only the size of the unsigned char array and then to define size of the int array automatically?
You could replace union with an array of chars, and convert void* pointer to int*, float*, etc. This would lead to a different syntax.

using #define for defining struct objects

I came across this simple program somewhere
#include<stdio.h>
#include<stdlib.h>
char buffer[2];
struct globals {
int value;
char type;
long tup;
};
#define G (*(struct globals*)&buffer)
int main ()
{
G.value = 233;
G.type = '*';
G.tup = 1234123;
printf("\nValue = %d\n",G.value);
printf("\ntype = %c\n",G.type);
printf("\ntup = %ld\n",G.tup);
return 0;
}
It's compiling (using gcc) and executing well and I get the following output:
Value = 233
type = *
tup = 1234123
I am not sure how the #define G statement is working.
How G is defined as an object of type struct globals ?
First, this code has undefined behavior, because it re-interprets a two-byte array as a much larger struct. Therefore, it is writing past the end of the allocated space. You could make your program valid by using the size of the struct to declare the buffer array, like this:
struct globals {
int value;
char type;
long tup;
};
char buffer[sizeof(struct globals)];
The #define is working in its usual way - by providing textual substitutions of the token G, as if you ran a search-and-replace in your favorite text editor. Preprocessor, the first stage of the C compiler, finds every entry G, and replaces it with (*(struct globals*)&buffer).
Once the preprocessor is done, the compiler sees this code:
int main ()
{
(*(struct globals*)&buffer).value = 233;
(*(struct globals*)&buffer).type = '*';
(*(struct globals*)&buffer).tup = 1234123;
printf("\nValue = %d\n",(*(struct globals*)&buffer).value);
printf("\ntype = %c\n",(*(struct globals*)&buffer).type);
printf("\ntup = %ld\n",(*(struct globals*)&buffer).tup);
return 0;
}
The macro simply casts the address of the 2-character buffer buf into a pointer to the appropriate structure type, then de-references that to produce a struct-typed lvalue. That's why the dot (.) struct-access operator works on G.
No idea why anyone would do this. I would think it much cleaner to convert to/from the character array when that is needed (which is "never" in the example code, but presumably it's used somewhere in the larger original code base), or use a union to get rid of the macro.
union {
struct {
int value;
/* ... */
} s;
char c[2];
} G;
G.s.value = 233; /* and so on */
is both cleaner and clearer. Note that the char array is too small.

Resources