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

Steven Schveighoffer schveiguy at gmail.com
Mon Oct 11 23:58:06 UTC 2021


On 10/10/21 6:44 AM, 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?

I know most of this is answered already, but I would suggest actually just:

```d
auto ppmalloc = &malloc;
```

which all of D's type inference to allow you to declare the appropriate 
function type.

BTW, you get the error because in D, empty parentheses are optional. So 
when you say `malloc`, it really means `malloc()`. Which is one big 
reason why the & operator is required.

-Steve


More information about the Digitalmars-d-learn mailing list