ImportC with Garbage Collector

Hipreme msnmancini at hotmail.com
Thu Apr 4 13:30:54 UTC 2024


On Thursday, 4 April 2024 at 09:52:14 UTC, Valthorn wrote:
> Hello, today I wrote the following code to try out ImportC:
>
> ```c
> // functions.c
> #include <stdio.h>
> #include <stdlib.h>
>
> void allocateMemory() {
>     int *data = (int *)malloc(1024 * 1024 * sizeof(int));
>
>     if (data == NULL) {
>         fprintf(stderr, "Memory could not be allocated.\n");
>         exit(EXIT_FAILURE);
>     }
>
>     printf("4MB of memory allocated.\n");
> }
> ```
>
> ```d
> // demo.d
> import std.stdio;
> import core.memory;
> import functions;
>
> void main() {
>     writeln("Before allocating memory. Memory: ", 
> GC.stats().usedSize, " bytes");
>     allocateMemory();
>     writeln("After allocating memory. Memory: ", 
> GC.stats().usedSize, " bytes");
>
>     GC.collect();
>     writeln("GC.collect() was called. Memory: ", 
> GC.stats().usedSize, " bytes");
> }
> ```
>
> Here I tried to check the operation of GC with ImportC, but 
> there's a situation I'm curious about. How exactly does ImportC 
> work? Can't it be used together with GC? Might there be an 
> ImportC update in the future that will also encompass the GC?


That would make sense if you posted on Learn by the way.

The thing is that `malloc` is completely unrelated to the `GC`. 
If you want to allocate using the garbage collector, in D, you 
would need to `import core.memory; GC.malloc(size);`. For usage 
in C, you would need to export that function and use it in C.
Also, managing a GC without a runtime is way harder since there 
is a lot of internal functions that mark your memory somehow for 
not collecting the memory you allocated.
That being said, IMO, importC should be preferred to only 
importing C code, and not for D code interaction since one would 
rather simply use D.


More information about the Digitalmars-d mailing list