Question

I am learning to call c in python program by CFFI and write c file named 'add.c' as below :

float add(float f1, float f2)
{
    return f1 + f2;
}

and a python file named 'demo.py' to call add method in 'add.c':

from cffi import FFI

ffi = FFI()
ffi.cdef("""
   float(float, float);
""")

C = ffi.verify("""
   #include 'add.c'
 """, libraries=[]
)

sum = C.add(1.9, 2.3)
print sum

When I run demo.py, I get the error that add.c file cannot be found. Why file add.c cannot be found and how can I to fix it?

Was it helpful?

Solution

I was able to reproduce your error with the following specific error message.

__pycache__/_cffi__x46e30051x63be181b.c:157:20: fatal error: add.c: No such file or 
directory
    #include "add.c"

It seems that cffi is trying to compile your file from inside the __pycache__ subdirectory, while add.c is in the current directory. The fix for this is to use the relative path

 #include "../add.c"

However, once I fixed that, your declaration was also incorrect, so I fixed that as well, and the following code produces correct results.

from cffi import FFI

ffi = FFI()
ffi.cdef("""
   float add(float f1, float f2);
""")

C = ffi.verify("""
   #include "../add.c"
 """, libraries=[]
)

sum = C.add(1.9, 2.3)
print sum
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top