How to do a function pointer to "malloc" and "free"?

Elmar chrehme at gmx.de
Sun Oct 10 11:26:18 UTC 2021


On Sunday, 10 October 2021 at 10:44:15 UTC, rempas wrote:
> I'm having the following C code:
>
> ```
> static void* (*ppmalloc)(size_t) = malloc;
> static void (*ppfree)(void*) = free;
> ```
>
> I want to covert this code in D so I try to do the following:
>
> ```
> static void* function(size_t)*ppmalloc = malloc;
> static void  function(void*)*ppfree = free;
> ```
>
> If I do that, I'm getting the following error message:
>
> ```
> Error: function `core.stdc.stdlib.malloc(ulong size)` is not 
> callable using argument types `()`
> ```
>
> I'm also trying to do the same using "pureMalloc" and 
> "pureFree" instead but this time I'm getting the following 
> error:
>
> ```
> cannot implicitly convert expression `pureMalloc()(size_t 
> size)` of type `void` to `extern (C) void* function(ulong)*`
> ```
>
> Any ideas?

Hello rempas.

This is the way:

```d
import core.stdc.stdlib : malloc, free;
extern(C) void* function(ulong) mallocPointer = &malloc;
extern(C) void function(void*) freePointer = &free;
```

`function` in the type is already a function pointer. Not 
immediately obvious though: You also must annotate the type with 
`extern(C)` otherwise it will not work.


More information about the Digitalmars-d-learn mailing list