Skip to content

Commit

Permalink
Merge branch 'main' into beta
Browse files Browse the repository at this point in the history
  • Loading branch information
TheTechsTech committed Mar 13, 2023
2 parents 6b33038 + 5214eed commit 9f0fb15
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
26 changes: 24 additions & 2 deletions preload.php
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ function ffi_char(string $string, bool $owned = false, bool $persistent = false)
}

/**
* Convert PHP array of `string` to `char**` _string_.
* Convert PHP array of `string` to `char**` _C string_.
*
* @param string $string
* @return CData __char**__
Expand All @@ -246,7 +246,29 @@ function ffi_char_variadic(string ...$string): CData
}
$string_args[$n] = NULL;

return \ze_cast('char**', $string_args);
return \FFI::cast('char**', $string_args);
}

/**
* Convert PHP associate array to _environment_ `char**` _C string_.
*
* @param array $env
* @return CData __char**__
*/
function ffi_char_assoc(array ...$items): CData
{
$i = 0;
$environment = \FFI::new('char*[' . (\count($items) + 1) . ']', false);
foreach ($items as $key => $value) {
$is = \is_array($value);
$key = $is ? \array_key_first($value) : $key;
$entry = \sprintf('%s=%s', $key, $is ? $value[$key] : $value);
$environment[$i] = \ffi_char($entry);
$i++;
}
$environment[$i] = NULL;

return \ze_cast('char**', $environment);
}

/**
Expand Down
23 changes: 23 additions & 0 deletions tests/902-misc_assoc_array_to_char_char.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
--TEST--
Check for ffi_char_assoc
--SKIPIF--
<?php if (!extension_loaded("ffi") || (('/' === DIRECTORY_SEPARATOR) && (PHP_OS !== 'Darwin') && ((float) \phpversion() < 8.0))) print "skip"; ?>
--FILE--
<?php
require 'vendor/autoload.php';

$env = ffi_char_assoc(["KEY" => "hello"], ["KEY1" => "hello1"]);
var_dump($env);
var_dump(ffi_string($env[0]));
var_dump(ffi_string($env[1]));

--EXPECTF--
object(FFI\CData:char**)#%d (1) {
[0]=>
object(FFI\CData:char*)#%d (1) {
[0]=>
string(1) "K"
}
}
string(9) "KEY=hello"
string(11) "KEY1=hello1"

0 comments on commit 9f0fb15

Please sign in to comment.