Skip to content

Instantly share code, notes, and snippets.

View sj-i's full-sized avatar

sji sj-i

View GitHub Profile
@sj-i
sj-i / ffi_callback.php
Created February 28, 2023 15:24
Example of creating a C structure with a function pointer via FFI, setting a PHP callback to that function pointer and calling it via FFI, and calling other PHP callbacks from within it
<?php
use FFI\CData;
$ffi = FFI::cdef(
<<<CDEF
typedef void (*func)(void (*callable1)(void), const char *(*callable2)(const char *));
struct tmp {
func fp;
};
@sj-i
sj-i / ffi_callback_memory_exhaustion.php
Created February 28, 2023 14:34
Passing a callback to PHP FFI eats up memory because some internal data is not released until the end of the request
<?php
use FFI\CData;
$ffi = FFI::cdef('void qsort(void *base, size_t num, size_t size, int (*compare)(const void*, const void*));');
$arr = FFI::new('int[2]');
$arr[0] = 1;
$arr[1] = 2;
while (true) {
@sj-i
sj-i / traits_usecases_and_weaknesses_and_future.md
Last active September 30, 2022 05:34
Should traits in PHP die or not?

I will introduce use cases for which traits can be useful in this post. It also mentions some weaknesses of traits, for helping considerations of alternatives.

This post was created as a response to a discussion I had when I submitted an RFC that would allow for constants in traits [1] and that it should not be improved because traits should die in the first place [2].

Use cases for traits

In my opinion, the following are possible valid use cases for traits, and actual use cases may be a combination of several of these.

  • Providing a default implementation of an interface
  • Achieving multiple inheritance
  • Splitting class implementations
@sj-i
sj-i / 001_testWideCharToMultiByte.php
Last active April 8, 2022 22:03
U+00A5 & U+203E to CP932, with or without 'best fit' mapping
<?php
declare(strict_types=1);
const WC_NO_BEST_FIT_CHARS = 0x00000400;
function test(string $utf8_str, bool $best_fit): void {
$ffi = \FFI::cdef(<<<CDECLS
int WideCharToMultiByte(
unsigned int CodePage,
@sj-i
sj-i / nfc-cardreader-example-written-in-php.php
Last active October 13, 2021 19:30 — forked from m3m0r7/nfc-cardreader-example-written-in-php.php
Example for using libnfc with written in PHP
<?php
/**
* Merged
* - https://github.com/nfc-tools/libnfc/blob/master/libnfc/nfc-internal.h
* - https://github.com/nfc-tools/libnfc/blob/2b5ad9ce0be19fbca5abc04b4ee0b59fb612e590/include/nfc/nfc-types.h
*
* @license https://github.com/nfc-tools/libnfc/blob/master/COPYING
*/
$ffi = FFI::cdef(<<<_
/**
@sj-i
sj-i / n-body-test-profile-result.md
Last active August 15, 2020 08:36
profiled https://gist.github.com/Girgias/e21b57cff72b8d05be06883d98552ee6 by using slightly modified version of sj-i/php-profiler,