I read it's possible to use C/C++ code in PHP by writing an extension. Is there a simpler way, like wrapping magic or things like that (I must say, I heard the word, but don't know much about what a wrapper is).
Compiling a php extension isn't very hard. There is a little API to learn just like C programs has the main function and how to pass variables to the main function.
No there is not.
PHP parses PHP not C or its decendants like C++
If you want to include C code in php like some function written in C then it has to be called in an extension and it has to be compiled.
A wrapper is code around code. Most any language you use like Delphi, Vb etc. have had native code created that then calls an external API function and in the process handles any type conversion required or parameter fix up.
Among others of the same kind, tcc can be used as a C interpreter. You can install it and then, from PHP, send a C program to it :)
$output = `echo -e '#include <stdio.h>\nint main(void) { printf("Hello, World!\\n"); return 0;}' | tcc -run -`;
tcc
is the one I like best. –
Orv It's not possible to write C or C++ inside of PHP Code. The only way you can go is writing an extension for PHP. Alternatively you can take a look at HipHop-PHP which transforms any PHP code into highly optimized C++ code (it's developed by Facebook).
Depending on what you want to do, you can just compile your code into an executable file and then start it in php e.g. via the exec-function.
If that is not enough, I am afraid you'll have to look into creating an extension - but that's not as hard as it sounds if you already know c or c++.
For the record:
Yes you can, using the FFI extension:
<?php
// create FFI object, loading libc and exporting function printf()
$ffi = FFI::cdef(
"int printf(const char *format, ...);", // this is a regular C declaration
"libc.so.6");
// call C's printf()
$ffi->printf("Hello %s!\n", "world");
?>
It will return
Hello world!
© 2022 - 2024 — McMap. All rights reserved.