Vtable for virtual functions in D

H. S. Teoh hsteoh at quickfur.ath.cx
Wed Mar 7 22:18:55 UTC 2018


On Wed, Mar 07, 2018 at 09:14:12PM +0000, Henrik via Digitalmars-d wrote:
[...]
> The direct support of C headers would be very convenient in migrating
> parts of C/C++ projects to D. It would also open up POSIX which is
> used extensively in our work.
[...]

There's already core.sys.posix.*, which are POSIX headers translated
into D, and which you can import and use right away. E.g.:

	import core.sys.posix.unistd;
	char[1024] buf;
	int fd = open("/tmp/file", O_RDONLY);
	auto len = read(fd, buf.ptr, buf.length);
	...
	close(fd);

Similarly, C standard library functions are directly available via
core.stdc.*:

	import core.stdc.stdlib;
	void* buf = malloc(1024);
	... // use buf here
	free(buf);

In principle, although direct support of C headers is not supported
(yet?), it's pretty easy to declare C functions in D and then just call
it directly, e.g.:

	// Declare C function here
	extern(C) size_t strlen(const(char)* s);

	void main()
	{
		import std.string : toStringz;

		// Call here
		auto len = strlen("blah blah".toStringz);
	}

In the above example I purposely used std.string to showcase how easy it
is to interoperate with C API functions, with toStringz and fromStringz
providing convenient conversions to/from C's char* strings.  The only
wrinkle here is that toStringz may allocate (because D strings are not
null-terminated in general), so cannot be used in @nogc code.

However, D string *literals* are always null-terminated, so the above
code could actually be replaced with just:

	auto len = strlen("blah blah".ptr);

and it will work in @nogc as well. Just be careful not to do that with
non-literal strings (or append a null manually and then it should be
safe).

The trouble with general C headers is that sometimes complicated macros
are used, and D does not come with a C macro processor, so it is tricky
to interface with those kinds of headers.  Still, if your code is not
directly dependent on the macros, you could just run the header through
a C preprocessor and then translate the C prototypes into D.  (There are
some cases for which this may not be so straightforward, but generally
you should be able to get quite far this way.)


T

-- 
Caffeine underflow. Brain dumped.


More information about the Digitalmars-d mailing list