Migrating PyCups to Python CFFI for libcups 3.x

Soumyadeep Ghosh <[email protected]> Wed, 02 Apr 2025 19:19:17 +0530
Newsgroups dev.linux.lists.printing-architecture
Message-ID <[email protected]>
Hello everyone,=20

This mail is after a long discussion with Till about various different appr=
oaches and possibilities. PyCups for libcups 2.4.x was written in C using t=
he Python's C extensions=20

The problem with that is:

1. Very low scope of automation
2.Very less support from different python communities
3.Only source of support is the original python documentation

With libcups 3.x, I am planning to move to use Python CFFI. With this, ther=
e is also a scope for automating the bindings too. For an example, how this=
 CFFI bindings work, sharing an example here

#include

const char* isPrime(int a){
=C2=A0 int i, flag=3D0;
=C2=A0 for(i=3D2;i
=C2=A0 {=C2=A0=C2=A0 if (a%i=3D=3D0)
=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0 (flag=3D1);
=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0 else
=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0 (flag=3D0);
=C2=A0 }
=C2=A0 if (flag=3D=3D1)
=C2=A0=C2=A0=C2=A0 return ("Number is Non-prime.");
=C2=A0 else
=C2=A0=C2=A0=C2=A0 return ("Number is Prime.");
}

int main()
{
=C2=A0=C2=A0=C2=A0 int n;
=C2=A0=C2=A0=C2=A0 printf("Enter any number:");
=C2=A0=C2=A0=C2=A0 scanf("%d",&n);
=C2=A0=C2=A0=C2=A0 isPrime(n);
}

This is a C function, and now, we complie this as a shared object and call =
this from python

from cffi import FFI

class DeterminePrime:
=C2=A0=C2=A0=C2=A0 def __init__(self, library_path=3D"../C programme/determ=
ine_prime.so"):
=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0 self.ffi =3D FFI()
=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0
=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0 self.ffi.cdef("""
=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0 const ch=
ar* isPrime(int);
=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0 """)
=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0
=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0 self.lib =3D self.ffi.dlopen(lib=
rary_path)

=C2=A0=C2=A0=C2=A0 def check_prime(self, number):
=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0 result =3D self.ffi.string(self.=
lib.isPrime(number))
=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0=C2=A0 return result.decode('utf-8')


As one can see, we just need the signature in many cases, to call the funct=
ion properly. Please let me know what you think about this change.


Thanks and Regards,
Soumyadeep Ghosh