Recent Changes - Search:

Oktatás

* Programozás 2
  + feladatsor
  + C feladatsor
  + Python feladatsor
  + GitHub oldal

* Szkriptnyelvek
  + feladatsor
  + quick link

* Adator. prog.
  + feladatsor
  + quick link

Teaching

* Prog. for Data Sci.
  ◇ exercises
  ◇ quick link

teaching assets


Félévek

* 2025/26/1
* archívum


Linkek

* kalendárium
   - munkaszüneti napok '20
* tételsorok
* jegyzetek
* szakdolgozat / PhD
* ösztöndíjak
* certificates
* C lang.
* C++
* C#
* Clojure
* D lang.
* Java
* Nim
* Scala


[ edit | logout ]
[ sandbox | passwd ]

Calling D from Python

Suppose we use Python and we have a very slow function. Idea: implement that function in D and use it as a library from Python.

Makefile:

cat:
	cat Makefile

so:
	# -shared → build a shared library
	# -fPIC → position-independent code (needed on Linux for shared libs)
	dmd -shared -fPIC mylib.d -of=libmylib.so

run:
	./main.py

Write the D library

(1) D library
extern (C) auto twice(const int n)
{
    return 2 * n;
}

Notes:

  • extern (C) doesn't mean that you have to write the code in C. It just means to use the C calling convention and symbol naming so other languages (like Python, Rust, etc.) can call this function.
  • I used the keyword auto, which doesn't exist in C. This is a D function.

Compile it with "make so" (see the Makefile above).

Write the main Python program

(2) the Python program
#!/usr/bin/env python3

from cffi import FFI

ffi = FFI()
lib = ffi.dlopen("./libmylib.so")
ffi.cdef("auto twice(const int n);")  # function declaration

def main():
    print(lib.twice(21))  # → 42

if __name__ == "__main__":
    main()

Notes:

  • The module cffi is a 3rd-party library. This is the Foreign Function Interface for Python calling C code. Under Manjaro, I had to install the package python-cffi (with pacman).
  • You need to declare the functions that you want to use.
  • Instead of cffi, you could also use the ctypes module. It's in the stdandard library, but its usage is a bit more complicated.

After this, you can execute your Python program:

$ ./main.py
42
Cloud City

  

Blogjaim, hobbi projektjeim

* The Ubuntu Incident
* Python Adventures
* @GitHub
* heroku
* extra
* haladó Python
* YouTube listák


Debrecen | la France


[ edit ]

Edit - History - Print *** Report - Recent Changes - Search
Page last modified on 2025 September 22, 15:53