Tuesday, September 20, 2016

Calling a simple C function from D - strcmp

By Vasudev Ram

D => C

It's quite useful to be able to communicate between modules of code written in different languages, or, in other words, to be able to call code in one language from code in another language. Some of the reasons why it is useful, are:

- some functions that you need may already be written in different languages, so it may be quicker to be able to call cross-language from function f1 in language L1 to function f2 in language L2, than to write both f1 and f2 in L1 (or in L2) from scratch;

- the function f2 that you need may not be as easy to write in language L1 as it is in language L2 (or you don't have people who can do it in L1 right now);

- f2 may run faster when written in L2 than in L1;

- etc.

I was looking into how to call C code from D code. One source of information is this page on the D site (from the section on the language spec):

Interfacing to C

Here is an example of calling a simple C function, strcmp from the standard C library, from a D program, adapted from information on that page:
File: call_strcmp.d
Purpose: Show how to call a simple C string function like strcmp from D.
Author: Vasudev Ram
Copyright 2016 Vasudev Ram
Web site: https://vasudevram.github.io
Blog: http://jugad2.blogspot.com

extern (C) int strcmp(const char* s, const char* t);

import std.stdio;
import std.string;

int use_strcmp(char[] s)
    // Use toStringz to convert s to a C-style NULL-terminated string.
    return strcmp(std.string.toStringz(s), "mango");

void main(string[] args)
    foreach(s; ["apple", "mango", "pear"])
        // Use dup to convert the immutable string s to a char[] so
        // it can be passed to use_strcmp.
        writeln("Compare \"", s.dup, "\" to \"mango\": ", use_strcmp(s.dup));
I compiled it with DMD (the Digital Mars D compiler):
$ dmd call_strcmp.d
and ran it:
$ call_strcmp
Compare "apple" to "mango": -1
Compare "mango" to "mango": 0
Compare "pear" to "mango": 1
The output shows that the C function strcmp does get called from the D program, and gives the right results, -1, 0, and 1, for the cases where the first argument was less than, equal to, or greater than the second argument (in sort order), respectively.

Of course, not all kinds of calls from D to C are going to be as easy as this (see the Interfacing reference linked above), but its nice that the easy things are easy (as the Perl folks say :).

- Vasudev Ram - Online Python training and consulting

Get updates on my software products / ebooks / courses.

Jump to posts: Python   DLang   xtopdf

Subscribe to my blog by email

My ActiveState recipes

No comments: