8

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?

apaderno
  • 28,547
  • 16
  • 75
  • 90
white_gecko
  • 4,808
  • 4
  • 55
  • 76

1 Answers1

10

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

Community
  • 1
  • 1
Jens A. Koch
  • 39,862
  • 13
  • 113
  • 141
  • Are you a Zephir guy? Do you use it for your projects? – Pacerier Feb 12 '15 at 14:56
  • 2
    More an allround PHP guy following trends in the community. Especially the performance oriented extensions like Phalcon and YAF got my attention. I've added Phalcon as default extension to my stack. – Jens A. Koch Feb 12 '15 at 15:13
  • I want to ask if zephir-lang can convert the php code to *C-source code* and then add it to `php` during compile time, I'm not sure about that, but in `FFMPEG` you can compile external libraries and embedded it to the final executable file. – Salem Apr 22 '22 at 16:28