PHP FFI - 将 void* 转换为 int

问题描述 投票:0回答:1

我有一个 C++ 函数,它将 int 转换为 void*。

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

在我的 PHP 代码中,我调用这个 C++ 函数并希望将其返回值转换为 int。

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

$voidptr = $ffi->get();

// convert void* to int

FFI::cast("int", $voidptr) 不起作用。 我尝试的唯一成功的方法是通过 print_r($voidptr, true); 打印 $voidptr,然后通过正则匹配得到 int 值。还有其他更好的办法吗?

感谢您的帮助。

php c++ ffi
1个回答
0
投票

有2种方法:

  1. 将返回值声明为int:

    $ffi = FFI::cdef(
           "int get();",
           "dllpath");
    $intval = $ffi->get();
    
  2. 创建一个 nullptr 并减去它:

    $nullptr = $ffi->cast('void*', 0);
    $intval = $voidptr - $nullptr;
    
© www.soinside.com 2019 - 2024. All rights reserved.