Search code examples
czephir

Is it possible with Zephir to include an external library?


I have some code in C which does some hardware access. This code is ready and well tested. Now I want to implement a web interface for controlling this hardware. So I came along PHP extension development with Zephir.

My question is, „Is it possible with Zephir to include an external library resp. link against it?“ and if it is possible, how can I do it?


Solution

  • Yes, it's possible and there are two approaches for working with C-code.

    By wrapping C-code in CBLOCKs

    You can embed c-code in tags, like so: %{ // c-code }%.

    This feature is undocumented, but exists in the tests.

    https://github.com/phalcon/zephir/blob/master/test/cblock.zep https://github.com/phalcon/zephir/blob/c47ebdb71b18f7d8b182f4da4a9c77f734ee9a71/test/cblock.zep#L16 https://github.com/phalcon/zephir/blob/c47ebdb71b18f7d8b182f4da4a9c77f734ee9a71/ext/test/cblock.c

    %{
        // include a header
        #include "headers/functions.h"
    
        // c implementation of fibonacci
        static long fibonacci(long n) {
            if (n < 2) return n;
            else return fibonacci(n - 2) + fibonacci(n - 1);
        }
    
    }%
    

    Looks a bit ugly, but works ,) A bit more elegant, but also more work, are custom optimizers:

    By writing a custom optimizer

    An ‘optimizer’ works like an interceptor for function calls. An ‘optimizer’ replaces the call for the function in the PHP userland by direct C-calls which are faster and have a lower overhead improving performance.

    It's possible to write an optimizer with a clean interfaces, allowing Zephir to know the parameter type passed forward to the C-function and the data type returned.

    Manual: https://docs.zephir-lang.com/en/latest/optimizers.html

    Example (call to fibonacci c-func): https://github.com/phalcon/zephir/pull/21#issuecomment-26178522