PHP FFI - Convert void* to int

57 Views Asked by At

I have a C++ function, it casts int to void*.

void* get() {
  int a = 555;
  return (void*)a;
}

In my PHP code, I call this C++ function and want to convert its return value to int.

$ffi = FFI::cdef(
  "void* get();",
  "dllpath");

$voidptr = $ffi->get();

// convert void* to int

FFI::cast("int", $voidptr) does not work. The only successful method I tried was to print the $voidptr through print_r($voidptr, true);, and then get the int value through regular matching. Is there any other better way?

thanks for your help.

1

There are 1 best solutions below

0
shingo On BEST ANSWER

There are 2 methods:

  1. Declare the return value as int:

    $ffi = FFI::cdef(
           "int get();",
           "dllpath");
    $intval = $ffi->get();
    
  2. Create a nullptr and subtract it:

    $nullptr = $ffi->cast('void*', 0);
    $intval = $voidptr - $nullptr;