Hi

Would you please teach me what's wrong with the following code?

I would like to pass a D function to a C function as a callback.
I could not figure it out what is wrong from the error message.

#### Error
````console
$ dub
...
    Building test ~master: building configuration [application]
src/main.d(8,6): Error: function `run` is not callable using argument types `(extern (C) int function())`
  run(&callback);
     ^
src/main.d(8,6): cannot pass argument `& callback` of type `extern (C) int function()` to parameter `extern (C) int function() fn` src/test.c(3,5): `test.run(extern (C) int function() fn)` declared here
int run(fp fn) {
    ^
````

#### Code
````d
// src/main.d

import test;

extern (C) int callback() {
  return 0;
}

auto main() {
  run(&callback);
}
````

````c
// src/test.h

typedef int(*fp)();

int run(fp);
````

````c
// src/test.c

typedef int(*fp)();

int run(fp fn) {
  return fn();
}
````

````
// dub.sdl

name "test"
targetType "executable"
mainSourceFile "src/main.d"
sourceFiles "src/test.c"
cImportPaths "src"
````

#### Compiler
````console
$ ldc2 -v
binary    .../ldc/ldc2-1.42.0-osx-arm64/bin/ldc2
version   1.42.0 (DMD v2.112.1, LLVM 21.1.8)
config .../ldc/ldc2-1.42.0-osx-arm64/etc/ldc2.conf (arm64-apple-darwin25.5.0)
````

#### It works when not using `ImportC`
````d
// src/main.d

extern (C) int run(int function());

extern (C) int callback() {
  return 0;
}

auto main() {
  run(&callback);
}
````

But I would like to know how to compile the code with `ImportC`.

Reply via email to