Interfacing with C libs: weeding through C/C++ macros and such in header files

Mike Parker aldacron at gmail.com
Mon Jan 14 05:23:06 UTC 2019


On Sunday, 13 January 2019 at 22:40:57 UTC, Alec Stewart wrote:

>
> Example without code; for some reason a macro is defined for 
> the stdlib functions `malloc`, `realloc`, and `free`. Maybe 
> it's just because I don't have any pro experience with C or 
> C++, but that seems a bit excessive. Or I could just be dumb.

Generally this is done to allow the compile-time configuration of 
memory allcoators. Back in my C days I had a little memory module 
that tracked total allocated and unallocated bytes and logged a 
few stats to a file at shutdown. I used macros to switch between 
it and the default stdlib calls.


> I understand what it's doing, but do I really any of this with 
> D?

No.

> And then there's this inline function
>
>     #define RS_DATA_SIZE(f, s, input)
>           \
> 	    do {
>    \
> 		    if (rs_is_heap(input))                                  \
> 			    f(s, input->heap.buffer, rs_heap_len(input));   \
> 		    else                                                    \
> 			    f(s, input->stack.buffer, rs_stack_len(input)); \
> 	    } while (0)
>

Generally, this sort of thing can be moved into a D function or 
template if it's repeated in several places. Without the 
do...while, of course. And in case you're unfamiliar with its 
purpose here:

https://stackoverflow.com/questions/154136/why-use-apparently-meaningless-do-while-and-if-else-statements-in-macros




More information about the Digitalmars-d-learn mailing list