I watched a very compelling lecture on unit testing C code with Python and I've been trying to write some test code using the strategy. When I attempted to run a very simple test, I receive the error:
cffi.api.CDefError: cannot parse "extern void *memcpy (void *__restrict __dest, const void *__restrict __src,":5:39: before: __dest
Is this a limitation of cffi that I can work around or am I just using it wrong?
For reference, the lecture is here: https://www.youtube.com/watch?v=zW_HyDTPjO0 and the slides with code snippets are here: https://ep2016.europython.eu/media/conference/slides/writing-unit-tests-for-c-code-in-python.html
My header file:
#include <string.h>
#ifndef _STRING_UTILS_H_
#define _STRING_UTILS_H_
extern int cmp(char* a, char* b);
#endif
My implementation:
#include <stringutils.h>
int cmp(char* a, char* b) {
return (strcmp(a, b) == 0);
}
The python file with the test in it:
#!/usr/bin/python3
import unittest
import cffi
import importlib
import pycparser
import subprocess
def preprocess(source):
return subprocess.run(['gcc', '-E', '-P', '-'],
input=source, stdout=subprocess.PIPE,
universal_newlines=True, check=True).stdout
def load(filename):
print('Loading ' + filename)
source = open(filename + '.c').read()
includes = preprocess(open(filename + '.h').read())
ffibuilder = cffi.FFI()
ffibuilder.cdef(includes)
print('21')
ffibuilder.set_source(filename + '_', source)
ffibuilder.compile()
module = importlib.import_module(filename + '_')
return module.lib
class StringUtilsTest(unittest.TestCase):
def test_cmp(self):
module = load('stringutils')
self.assertTrue(module.cmp('howdy', 'howdy'))
self.assertFalse(module.cmp('howdy', 'haudy'))
#run(StringUtilsTest)
if __name__ == '__main__':
unittest.main()
Is this something to do with the *__restrict
declaration it has?
I have never attempted to mix Python and C in this source-aware way before. Thanks in advance.