Showing posts with label cross-language-calling. Show all posts
Showing posts with label cross-language-calling. Show all posts

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



Sunday, May 8, 2016

Calling C from Python with ctypes

By Vasudev Ram

Python => C

ctypes is a module in the Python standard library. It is "a foreign function library for Python". Such libraries help with calling code written in language B, from language A. In the case of ctypes it helps with calling C code from Python code.

[ Note: There are various other methods of linking between Python code and code written in other languages, such as writing Python extensions using the Python C API, SWIG, cffi, etc. I am only looking at ctypes in this post. It is one of the simpler methods. May look at others later. ]

Here is a small example of using ctypes, to call the time() function in the C runtime library on Windows:

# libc_time.py
# Example of calling C library functions from Python
# using the Python ctypes module.
# Author: Vasudev Ram
# Copyright 2016 Vasudev Ram

from __future__ import print_function
from ctypes import cdll
import time

libc = cdll.msvcrt

def test_libc_time(n_secs):
    t1 = libc.time(None)
    time.sleep(n_secs)
    t2 = libc.time(None)
    print("n_secs = {}, int(t2 - t1) = {}".format(n_secs, int(t2 - t1)))
    
print("Calling the C standard library's time() function via ctypes:")
for i in range(1, 6):
    test_libc_time(i)
And here is the output:
$ python libc_time.py
Calling the C standard library's time() function via ctypes:
n_secs = 1, int(t2 - t1) = 1
n_secs = 2, int(t2 - t1) = 2
n_secs = 3, int(t2 - t1) = 3
n_secs = 4, int(t2 - t1) = 4
n_secs = 5, int(t2 - t1) = 5
Note: libc.time() is the Python interface [1] to the C time() function, and time.sleep() is the sleep function in the time module of the Python standard library.

[1] We obtain that interface using ctypes; see the program above.

I use a call to time.sleep() sandwiched between two calls to libc.time(), to verify that the calls to libc.time() are returning the correct result; as you can see from the output, they are doing so.

- Vasudev Ram - Online Python training and consulting

Signup to hear about my new courses and products.

My Python posts     Subscribe to my blog by email

My ActiveState recipes



Saturday, August 25, 2012

Cython: combined power of C and Python; call back and forth between Python and C/C++

By Vasudev Ram


Cython - (Cython on Wikipedia) is "a language that makes writing C extensions for the Python language as easy as Python itself. It is based on the well-known Pyrex, but supports more cutting edge functionality and optimizations."

Excerpts:

[ Cython gives you the combined power of Python and C to let you:

- write Python code that calls back and forth from and to C or C++ code natively at any point.

- easily tune readable Python code into plain C performance by adding static type declarations.

- use combined source code level debugging to find bugs in your Python, Cython and C code.

- integrate natively with existing code and data in legacy, low-level or high-performance libraries and applications.

]

Excerpts from Wikipedia:

[

Cython is particularly popular among scientific users of Python,[11][16][17] where it has "the perfect audience" according to Python developer Guido van Rossum.[18] Of particular note:

The free software Sage computer algebra system depends on Cython, both for performance and to interface with other libraries.[19]
Significant parts of the scientific and numerical computing libraries SciPy and NumPy are written in Cython.[20][21]
Cython's domain is not limited to just numerical computing. For example, the lxml XML toolkit is written mostly in Cython, and Cython is used to provide Pythonic bindings for many C and C++ libraries ranging from the graphics library OpenGL[22] to the messaging library ZeroMQ.[23]

]

- Vasudev Ram - Dancing Bison Enterprises