0

I'm working on a cffi testing demo, and when I try to run the python tester file, it returns the following error: TypeError: initializer for ctype 'Car *' appears indeed to be 'Car *', but the types are different (check that you are not e.g. mixing up different ffi instances)

The car.h file defines the C structure Car and is shown here:

/*Class definition for car*/
     typedef struct {
     char make[32];
     char model[32];
     char year[32];
     char color[32];
     } Car;

Here is the python file using cffi that I'm trying to use to test the C code.

import unittest
import cffi
import importlib

ffi=cffi.FFI()
def load(filename):
    #load source code
    source = open('../src/' + filename + '.c').read()
    includes = open('../include/' + filename + '.h').read()

    #pass source code to CFFI
    ffi.cdef(includes)
    ffi.set_source(filename + '_', source)
    ffi.compile()

    #import and return resulting module
    module = importlib.import_module(filename + '_')
    return module.lib

class carTest(unittest.TestCase):
    def test_setMake(self):
        module = load('car')

        myCar = ffi.new('Car *',
           ["Honda", "Civic", "1996", "Black"])
        make = ("char []", "Honda")

        self.assertEqual(module.setMake(myCar, make),
                car)

if __name__ == '__main__':
    unittest.main()

Any advice on this issue would be very welcome. I feel like I've gone over it a hundred times.

Thanks in advance

1 Answers1

0

It's because you are mixing two unrelated ffi instance. There is the one you explicitly create and use inside the load() function to make the C extension module; in this kind of usage we recommend to call it ffibuilder instead of ffi. But then you import the compiled module, and you get a different ffi instance as module.ffi; that one comes from the C extension module. Ideally, you should no longer use the ffibuilder after compilation.

I would recommend to change load() to return both module.ffi and module.lib (or maybe just module), kill the global ffi declaration, and make locally a ffibuilder = cffi.FFI() inside the load() function.

Armin Rigo
  • 12,048
  • 37
  • 48