Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible with Zephir to include an external library?

Tags:

c

zephir

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?

like image 729
white_gecko Avatar asked Sep 11 '14 21:09

white_gecko


People also ask

What is an external library?

What are External Libraries? External Libraries are pieces of pre-written code that is easy to implement. You don't really have to know exactly anything about what is inside that code, you just need to know how to use it.


1 Answers

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

like image 52
Jens A. Koch Avatar answered Nov 11 '22 02:11

Jens A. Koch