-
Notifications
You must be signed in to change notification settings - Fork 6
/
FFIAdapter.php
109 lines (92 loc) · 2.58 KB
/
FFIAdapter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
declare(strict_types=1);
namespace Extraton\TonClient\FFI;
use FFI;
use FFI\CData;
use RuntimeException;
class FFIAdapter
{
private string $libraryInterface;
private string $libraryPath;
private ?FFI $ffi = null;
/**
* @param string $libraryInterface
* @param string $libraryPath
*/
public function __construct(string $libraryInterface, string $libraryPath)
{
$this->libraryInterface = $libraryInterface;
$this->libraryPath = $libraryPath;
}
/**
* @param string $functionName
* @param array<mixed> $arguments
* @return CData
*/
public function __call(string $functionName, array $arguments = []): FFI\CData
{
return $this->call($functionName, $arguments);
}
/**
* @param string $functionName
* @param array<mixed> $arguments
* @return CData
*/
public function call(string $functionName, array $arguments = []): FFI\CData
{
return $this->getFFI()->{$functionName}(...$arguments);
}
public function getFFI(): FFI
{
if ($this->ffi === null) {
$this->ffi = FFI::cdef(
$this->getLibraryInterface(),
$this->getLibraryPath()
);
}
return $this->ffi;
}
public function getLibraryInterface(): string
{
return $this->libraryInterface;
}
public function getLibraryPath(): string
{
return $this->libraryPath;
}
/**
* @param string $type
* @param bool $owned
* @return CData
*/
public function callNew(string $type, bool $owned = true): FFI\CData
{
$cData = $this->getFFI()->new($type, $owned);
if ($cData === null) {
throw new RuntimeException('Invalid data from call FFI::new().');
}
return $cData;
}
/**
* Creates a PHP string from a memory area
*
* @param CData $ptr The start of the memory area from which to create a string
* @param int $size The number of bytes to copy to the string
* @return string
*/
public function callString(CData $ptr, int $size): string
{
return FFI::string($ptr, $size);
}
/**
* Copies one memory area to another
*
* @param CData $destination The start of the memory area to copy to
* @param string $source The start of the memory area to copy from
* @param int $size The number of bytes to copy
*/
public function callMemCpy(CData $destination, string $source, int $size): void
{
FFI::memcpy($destination, $source, $size);
}
}