Claudiu Persoiu

Blog-ul lui Claudiu Persoiu


Archive for the ‘Go’ tag

A bit of PHP, Go, FFI and holiday spirit

without comments

Ah, the holiday spirit.

Inspired by a post in Perl Advent, I decided that it would be nice to see an example done with PHP and Go. Please note that this blog is heavily inspired by the post mentioned above.

Let’s say you want to wish upon others happy holiday using the speed of Go, but you are using PHP, what is there to be done?

This is a great time in the PHP world to do something like this, as the newly released PHP 7.4 comes with “Foreign Function Interface” (FFI for short).

Equipped with this new power, I installed PHP 7.4 and got to work.

Let’s start with the super incredible Go greeting part, let’s create a file “greeting.go”:

package main
 
import (
   "fmt"
)
 
func main() {
   WishMerryChristmas();
}
 
func WishMerryChristmas() {
   fmt.Println("We wish you a Merry Christmas!");
}

Now let’s run it with:

$ go run greeting.go

It should display:
We wish you a Merry Christmas!

Great stuff so far! Now this is nice and fast and everything, but it needs to be a service, let’s see how that would look like:

package main
 
import (
   "C"
   "fmt"
)
 
func main() {}
 
//export WishMerryChristmas
func WishMerryChristmas() {
   fmt.Println("We wish you a Merry Christmas!")
}

As you can see, there are several differences:

  • we also imported “C”,
  • we removed the function call from main()
  • we added a comment to export the function.

To compile the code, run:

$ go build -o greeting.so -buildmode=c-shared

Note that this should be run each time the Go file is modified.

The output should be two files: “greeting.so” and “greeting.h”.

The header file “greeting.h” file contains the types and functions definition. If you come from C world you are probably already familiar with this type of files. Normally, all we need to do now is to import the header file using FFI and use the function!

For this I’ve created a file titled “greeting.php”:

<?php
 
$ffi = FFI::load("greeting.h");
$ffi->WishMerryChristmas();

Sure looks simple enough, you just have to run it with:

$ php greeting.php 
PHP Fatal error:  Uncaught FFI\ParserException: undefined C type '__SIZE_TYPE__' at line 43 in /home/claudiu/php-go/greeting.php:3
Stack trace:
#0 /home/claudiu/php-go/greeting.php(3): FFI::load()
#1 {main}

Next FFI\Exception: Failed loading 'greeting.h' in /home/claudiu/php-go/greeting.php:3
Stack trace:
#0 /home/claudiu/php-go/greeting.php(3): FFI::load()
#1 {main}
  thrown in /home/claudiu/php-go/greeting.php on line 3

Not exactly the greeting that I was hoping for…

After some digging, I found this one on the manual page:
C preprocessor directives are not supported, i.e. #include, #define and CPP macros do not work.

Because of this, we unfortunately can’t really use the header file, or at least I don’t know how.

On the bright side, we can use FFI::cdef() which allows for function definition specification. If I lost you on the way, what I’m trying to do is just tell PHP which are the function definitions that it can use from “greeting.so”.

The new code will become:

<?php
$ffi = FFI::cdef("
void WishMerryChristmas();
", __DIR__ . "/greeting.so");

$ffi->WishMerryChristmas();

And if we run it:

$ php greeting.php
We wish you a Merry Christmas!

We are making great progress, the service is doing a great job!

Adding an int parameter

The greeting is nice and fast and all but it would be nice to be able to specify how many times to run it.

To achieve this, I’m modifying the previous example method to specify how many times to display the greeting in the file greeting.go:

//export WishMerryChristmas
func WishMerryChristmas(number int) {
   for i := 0; i < number; i++ {
       fmt.Println("We wish you a Merry Christmas!");
   }
}

Run the compilation as before and everything should be fine.

In the PHP script we need to modify the function definition. To see what we should use we can take a hint from the “greeting.h” file. The new function definition in my file is:

extern void WishMerryChristmas(GoInt p0);

“GoInt”? What magic is that? Well, if we look in the file, there are the following definitions:

...
typedef long long GoInt64;
...
typedef GoInt64 GoInt;
...

With this in mind, we can change the PHP file to:

<?php
$ffi = FFI::cdef("
void WishMerryChristmas(long);
", __DIR__ . "/greeting.so");
 
$ffi->WishMerryChristmas(3);

Run it and you should see:

$ php greeting.php 
We wish you a Merry Christmas!
We wish you a Merry Christmas!
We wish you a Merry Christmas!

Ah, it’s beginning to feel a lot like Christmas!

Adding a string parameter

Displaying a greeting multiple times is quite nice, but it would be nicer to add a name to it.

The new greeting function in go will be:

//export WishMerryChristmas
func WishMerryChristmas(name string, number int) {
   for i := 0; i < number; i++ {
       fmt.Printf("We wish you a Merry Christmas, %s!\n", name);
   }
}

Don’t forget to compile and let’s get to the interesting part.

Looking into the “greeting.h” file, the new function definition is:

extern void WishMerryChristmas(GoString p0, GoInt p1);

We already got GoInt, but GoString it is a bit trickier. After several substitutions I was able to see that the structure is:

typedef struct { char* p; long n } GoString;

It is essentially a pointer to a list of characters and a dimension.

This means that, in the PHP file, the new definition is going to be:

$ffi = FFI::cdef("
typedef struct { char* p; long n } GoString;
typedef long GoInt;
void WishMerryChristmas(GoString p0, GoInt p1);
", __DIR__ . "/greeting.so");

p0 and p1 are optional, but I’ve added them for a closer resemblance to the header file. On the same note, GoInt is basically a long, but I left the type there for the same reason.

Building a GoString was a bit of a challenge. The main reason is that I didn’t find a way to create a “char *” and initialize it. My alternative was to create an array of “char” and cast it, like this:

$name = "reader";
$strChar = str_split($name);
 
$c = FFI::new('char[' . count($strChar) . ']');
foreach ($strChar as $i => $char) {
   $c[$i] = $char;
}
 
$goStr = $ffi->new("GoString");
$goStr->p = FFI::cast(FFI::type('char *'), $c);
$goStr->n = count($strChar);
 
$ffi->WishMerryChristmas($goStr, 2);

And let’s try it out:

$ php greeting.php 
We wish you a Merry Christmas, reader!
We wish you a Merry Christmas, reader!

Success!

At this point I would like to move the GoString creation in a new function, just for the sake of code clean-up.

And the new code is:

$name = "reader";

$goStr = stringToGoString($ffi->new("GoString"), $name);

$ffi->WishMerryChristmas($goStr, 2);

function stringToGoString($goStr, $name) {
    $strChar = str_split($name);

    $c = FFI::new('char[' . count($strChar) . ']');
    foreach ($strChar as $i => $char) {
        $c[$i] = $char;
    }
    
    $goStr->p = FFI::cast(FFI::type('char *'), $c);
    $goStr->n = count($strChar);

    return $goStr;
}

And let’s try it:

$ php greeting.php 
We wish you a Merry Christmas, ��!
We wish you a Merry Christmas, ��!

That’s not right… it seems like it’s displaying some junk memory. But why?

Looking into the documentation for FFI::new I’ve seen a second parameter “bool $owned = TRUE”.
Whether to create owned (i.e. managed) or unmanaged data. Managed data lives together with the returned FFI\CData object, and is released when the last reference to that object is released by regular PHP reference counting or GC. Unmanaged data should be released by calling FFI::free(), when no longer needed.

This means that, when the function was returned, the GC is clearing the memory for the string. This is very likely a bug, but there is a very simple fix, just modify the char array creation to “false”:

$c = FFI::new('char[' . count($strChar) . ']', false);

Let’s try it again:

$ php greeting.php 
We wish you a Merry Christmas, reader!
We wish you a Merry Christmas, reader!

And it’s working!

Conclusion

Maybe it’s not as easy as importing a header file when trying to run Go libraries from PHP, but with a little patience it is certainly possible! A big advantage to this is that a library built in Go, or other programming languages that allow it, can be used by a language like PHP without the need to reimplement the logic!

And, on this last positive remark, I would like to wish you happy holidays!

Written by Claudiu Persoiu

23 December 2019 at 1:37 PM

Posted in GO,PHP

Tagged with , , ,