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 ]

Passing a list of integers

We want to pass a list of integers from Python to D.

Notes:

  • In Python, a list (e.g. li = [1, 2, 3]) is different from a C array. If we want to pass it to a D function, first we need to convert it to a C array.
  • A D slice is a fat pointer, a combination of a pointer and length. So we pass these two data to the D function.

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

D code

(1) D code
extern (C) int mysum(const int* numbers, const size_t length)
{
    import std.algorithm : sum;

    // convert pointer + length into a D slice
    auto slice = numbers[0 .. length];
    return slice.sum();
}

Python code

(2) Python code
#!/usr/bin/env python3

from cffi import FFI

ffi = FFI()
lib = ffi.dlopen("./libmylib.so")
ffi.cdef("int mysum(const int* numbers, const size_t length);")

def carray(lst):
    """Convert a Python list of ints to a cffi C array"""
    return ffi.new("int[]", lst)

def main():
    li = [1, 2, 3]
    print(lib.mysum(carray(li), len(li)))

if __name__ == "__main__":
    main()

After this, you can execute your Python program:

$ ./main.py
6
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, 16:35