How to call a C function from D that takes a FILE * as an argument?
Seb
seb at wilzba.ch
Wed Jul 4 01:58:15 UTC 2018
On Wednesday, 4 July 2018 at 01:06:36 UTC, Joe wrote:
> The subject basically says it all. The C function uses the
> argument to call fprintf and also passes it to other functions
> where it's used to call fileno, fprintf or putc.
Like you would with C's fprintf
(https://dlang.org/phobos/core_stdc_stdio.html#.fprintf).
For example, this is a valid D program:
---
void main(string[] args)
{
import core.stdc.stdio;
FILE* pFile;
int n;
char[100] name;
pFile = fopen ("myfile.txt","w"); // string literals are
zero-terminated
for (n=0 ; n<3 ; n++)
{
puts("please, enter a name: ");
gets(name.ptr);
fprintf pFile, "Name %d [%-10.10s]\n",n+1,name.ptr);
}
fclose(pFile);
}
---
(example from http://www.cplusplus.com/reference/cstdio/fprintf)
So just add the declaration to your D file:
---
extern(C) void myCfunction(FILE* stream);
---
and as long as you link your program into the D binary, you
should be good to go.
For larger C bases, tools like dstep or dpp can help translating
C/C++ header files to D.
More information about the Digitalmars-d-learn
mailing list