Symisc PH7 Engine
An Embeddable PHP5 Engine

PH7 C/C++ API Reference - List Of Functions.

This is a list of all functions and methods operating on the objects and using and/or returning constants. There are many functions, but most applications only use a handful.


Engine Handling Interfaces

Compile Interfaces

Virtual Machine Handling Interfaces

In-process Extending Interfaces

Foreign Function Parameter Values

Setting The Result Of A Foreign Function

Call Context handling Interfaces

Call Context Memory Management Interfaces

Dynamically Typed Value Object Management Interfaces

Global Library Management Interfaces

On Demand Dynamically Typed Value Object allocation interfaces




ph7_init

int ph7_init(ph7 **ppEngine);

Allocate and initialize a new PH7 engine instance.

Description

This routine create, initialize and returns a new PH7 engine instance. This is often the first PH7 API call that an application makes and is a prerequisite in order to compile PHP code using one of the compile interfaces.

Parameters

ppEngine

OUT: A pointer to a freshly initialized PH7 engine is stored here. When something goes wrong, this pointer is left pointing to NULL.

Return value

PH7_OK is returned on success. Any other return value typically PH7_NOMEM (Out of memory) indicates failure and the caller must discard the ppEngine pointer.


ph7_config

int ph7_config(ph7 *pEngine,int nConfigOp,...);

Configure a PH7 engine instance.

Description

This routine is used to configure a working PH7 engine instance created by a prior successful call to ph7_init().

The second argument to ph7_config() is an integer configuration option that determines what property of PH7 is to be configured. Subsequent arguments vary depending on the configuration option in the second argument. Here is the list of allowed verbs

Configuration Verb

Expected Arguments

Description

PH7_CONFIG_ERR_LOG

Two Arguments:

const char **pzPtr,

int *pLen;


When something goes wrong while compiling a PHP script due to an erroneous PHP code, the engine error log is redirected to an internal buffer. This option is used to extract that error log. The first argument this option takes is a pointer address of type const char. This pointer will be automatically set by the engine to point to the error log buffer which is a null terminated string.

The second argument this option takes is an optional pointer to an integer. When set (I.e: not null), the integer value will hold the length of the error log buffer.

Example:

const char *zErrLog;

int nLen;

/* Extract error log */

ph7_config(

   pEngine,

   PH7_CONFIG_ERR_LOG,

   &zErrLog, /* First arg*/

   &nLen /* Second arg */

);

if( nLen > 0 ){

   puts(zErrLog); /* Output*/

}

PH7_CONFIG_ERR_OUTPUT

Two Arguments:

int (*xConsumer)(

     const void *pErrMsg,

     unsigned int msg_len,

     void *pUserData

),

void *pUserData;

Rather than redirecting the error log to an internal buffer, sometimes it's more efficient to redirect the error log to an user defined function which is responsible of consuming the error log perhaps redirecting it to STDERR or something like that. This option perform the requested operation, the first argument this option takes is a pointer to a host application defined function that is responsible of consuming the error log. The callback must take three parameters. The first parameter is the error log message which is not null terminated, the second parameter is the error log length in bytes (The engine guarantee this number is always greater than zero) and the last parameter is an arbitrary user pointer forwarded verbatim by the engine to the callback.

The second argument this option takes is the user pointer which is forwarded verbatim by the engine as the last argument to the callback.

You can refer to the source code of the PH7 interpreter at the download page for a working example.

PH7_CONFIG_ERR_ABORT

No Arguments

This configuration verb is reserved for future use and is a no-op in the current release of the PH7 engine.

Parameters

pEngine

A pointer to a correctly initialized PH7 engine.

nConfigOp

An integer configuration option that determines what property of the PH7 engine is to be configured.

Return value

PH7_OK is returned on success. Any other return value typically PH7_CORRUPT (Unknown configuration verb) indicates failure.


ph7_release

int ph7_release(ph7 *pEngine);

Destroy a PH7 engine instance.

Description

This routine destroy a working PH7 engine instance created by a prior successful call to ph7_init(). Every PH7 engine must be destroyed using a call to this routine in order to avoid memory leaks .

Parameters

pEngine

A pointer to a correctly initialized PH7 engine.

Return value

PH7_OK is returned on success. Any other return value indicates failure.


ph7_compile

int ph7_compile(

    ph7 *pEngine,

    const char *zSource,

    int nLen,

    ph7_vm **ppOutVm

);

Compile a PHP program to PH7 bytecodes (Old interface).

Description

Note: This is the old interface and is provided here for backward compatibility. New code should use the ph7_compile_v2() interface.

To execute PHP code, it must first be compiled into a bytecode program using one of the compile routines.

This routine takes as its input a PHP program to compile and produce PH7 bytecodes represented by an opaque pointer to the ph7_vm structure.

This API does not actually evaluate the PHP code. It merely prepares the PHP code for later execution.

On successful compilation, the compiled program is stored in the ppOutVm pointer (Fourth parameter) and the program is ready for execution using ph7_vm_exec(). When something goes wrong while compiling the PHP script due to a compile-time error, the caller must discard the ppOutVm pointer and fix its erroneous PHP code. The compile-time error log can be extracted using the ph7_config() interface with a configuration verb set to:

PH7_CONFIG_ERR_OUTPUT or PH7_CONFIG_ERR_LOG

Parameters

pEngine

A pointer to a correctly initialized PH7 engine.

zSource

PHP code to compile. The code to compile must be delimited by one of the standard PHP tags such as <?php ?> or <? ?> as follows:

<html>

<body>

<?php

echo “Hello world!!”;

?>

</html>

</body>

Otherwise if the PHP code is not delimited, your VM output should be a copy of the source without any evaluation.

nLen

Source length. If the nLen argument is less than zero, then zSource is read up to the first zero terminator. If nLen is non-negative, then it is the maximum number of bytes read from zSource.

ppOutVm

Out: On successful compilation, *ppOutVm is left pointing to the compiled PHP program represented by an opaque pointer to the ph7_vm structure. It's safe now to call one of the VM management interfaces such as ph7_vm_config() and the compiled program can be executed using ph7_vm_exec(). Otherwise *ppOutVM is left pointing to NULL.

Return value

PH7_OK is returned on success. Any other return value indicates failure such as:

PH7_COMPILE_ERR is returned when compile-time errors occurs. That is, the caller must fix its erroneous PHP code and call the compile interface again.

Note that the compile-time error log can be extracted using the ph7_config() interface with a configuration verb set to:

PH7_CONFIG_ERR_OUTPUT or PH7_CONFIG_ERR_LOG

PH7_VM_ERR is returned when there is an error while initializing the virtual machine typically due to a memory failure problem, but remember this is a very unlikely scenario on modern hardware, even on modern embedded system.

Example

Download this C file for a smart introduction to the compile interfaces.


ph7_compile_v2

int ph7_compile_v2(

    ph7 *pEngine,

    const char *zSource,

    int nLen,

    ph7_vm **ppOutVm,

    int iFlags

);

Compile a PHP program to PH7 bytecodes (Recommended interface).

Description

To execute PHP code, it must first be compiled into a bytecode program using one of the compile routines.

This routine takes as its input a PHP program to compile and produce PH7 bytecodes represented by an opaque pointer to the ph7_vm structure.

This API does not actually evaluate the PHP code. It merely prepares the PHP code for later execution.

On successful compilation, the compiled program is stored in the ppOutVm pointer (Fourth parameter) and the program is ready for execution using ph7_vm_exec(). When something goes wrong while compiling the PHP program due to a compile-time error, the caller must discard the ppOutVm pointer and fix its erroneous PHP code. The compile-time error log can be extracted using the ph7_config() interface with a configuration verb set to:

PH7_CONFIG_ERR_OUTPUT or PH7_CONFIG_ERR_LOG

Parameters

pEngine

A pointer to a correctly initialized PH7 engine.

zSource

PHP code to compile. If the PH7_PHP_ONLY compile flag is not set, then the code to compile must be delimited by the standard PHP tags such as <?php ?> or <? ?> as follows:

<html>

<body>

<?php

echo “Hello world!!”;

?>

</html>

</body>

Otherwise if the PHP code is not delimited and the PH7_PHP_ONLY flag is not set your VM output should be a copy of the source without any evaluation.

nLen

Source length. If the nLen argument is less than zero, then zSource is read up to the first zero terminator. If nLen is non-negative, then it is the maximum number of bytes read from zSource.

ppOutVm

Out: On a successful compilation, *ppOutVm is left pointing to the compiled PHP program represented by an opaque pointer to the ph7_vm structure. It's safe now to call one of the VM management interfaces such as ph7_vm_config() and the compiled program can be executed using ph7_vm_exec(). Otherwise *ppOutVM is left pointing to NULL.

iFlags

Optional: Zero or more combination of compile-time flags, these are:

PH7_PHP_ONLY

If this flag is set then the code to compile is assumed to be plain PHP only. That is, there is no need to delimit the PHP code using the standard tags such as <?php ?> or <? ?>. Everything will pass through the PH7 compiler.

PH7_PHP_EXPR

This flag is reserved for future use.


Otherwise pass 0 (zero) for the default behavior.

Return value

PH7_OK is returned on success. Any other return value indicates failure such as:


PH7_COMPILE_ERR is returned when compile-time errors occurs. That is, the caller must fix its erroneous PHP code and call the compile interface again.

Note that the compile-time error log can be extracted using the ph7_config() interface with a configuration verb set to:

PH7_CONFIG_ERR_OUTPUT or PH7_CONFIG_ERR_LOG


PH7_VM_ERR is returned when there is an error while initializing the virtual machine typically due to a memory failure problem but remember this a very unlikely scenario on modern hardware, even on modern embedded system.

Example

Download this C file for a smart introduction to the compile interfaces.


ph7_compile_file

int ph7_compile_file(

    ph7 *pEngine,

    const char *zFilePath,

    ph7_vm **ppOutVm,

    int iFlags

);

Compile a PHP File to PH7 bytecodes.

Description

To execute PHP code, it must first be compiled into a bytecode program using one of the compile routines.

This routine takes as its input a PHP file to compile and produce PH7 bytecodes represented by an opaque pointer to the ph7_vm structure.

This API does not actually evaluate the PHP code. It merely prepares the PHP code for later execution.

On successful compilation, the compiled program is stored in the ppOutVm pointer (Third parameter) and the program is ready for execution using ph7_vm_exec(). When something goes wrong while compiling the PHP program due to a compile-time error, the caller must discard the ppOutVm pointer and fix its erroneous PHP code. The compile-time error log can be extracted using the ph7_config() interface with a configuration verb set to:

PH7_CONFIG_ERR_OUTPUT or PH7_CONFIG_ERR_LOG

Parameters

pEngine

A pointer to a correctly initialized PH7 engine.

zFilePath

Relative or full path to the PHP file to compile. If the PH7_PHP_ONLY compile flag is not set, then the code to compile must be delimited by the standard PHP tags such as <?php ?> or <? ?> as follows:

<html>

<body>

<?php

echo “Hello world!!”;

?>

</html>

</body>

Otherwise if the PHP code is not delimited and the PH7_PHP_ONLY flag is not set your VM output should be a copy of the source without any evaluation.

Note that this function depends on the xmmap() routine of the underlying VFS. In other words it tries to get a read-only memory view of the whole file. Windows and UNIX users don't have to worry about these details,since PH7 come with a built-in VFS that handle all the stuff. But others platforms must register their own VFS (Virtual File System) that implements the xmmap() routine. Otherwise this function fails and returns PH7_IO_ERR.

ppOutVm

Out: On a successful compilation, *ppOutVm is left pointing to the compiled PHP program represented by an opaque pointer to the ph7_vm structure. It's safe now to call one of the VM management interfaces such as ph7_vm_config() and the compiled program can be executed using ph7_vm_exec(). Otherwise *ppOutVM is left pointing to NULL.

iFlags

Optional: Zero or more combination of compile-time flags,these are:

PH7_PHP_ONLY

If this flag is set then the code to compile is assumed to be plain PHP only. That is,there is no need to delimit the PHP code using the standard tags such as <?php ?> or <? ?>. Everything will pass through the PH7 compiler.

PH7_PHP_EXPR

This flag is reserved for future use.


Otherwise pass 0 (zero) for the default behavior.

Return value

PH7_OK is returned on success. Any other return value indicates failure such as:

PH7_COMPILE_ERR is returned when compile-time errors occurs. That is, the caller must fix its erroneous PHP code and call the compile interface again.

Note that the compile-time error log can be extracted using the ph7_config() interface with a configuration verb set to:

PH7_CONFIG_ERR_OUTPUT or PH7_CONFIG_ERR_LOG


PH7_VM_ERR is returned when there is an error while initializing the virtual machine typically due to a memory failure problem but remember this a very unlikely scenario on modern hardware, even on modern embedded system.


PH7_IO_ERR is returned when IO errors occurs (ie: permission error, nonexistant file, etc) or the underlying VFS does not implement the xmmap() method which is not the case when the built-in VFS is used (default case).

Example

Download this C file for a smart introduction to the compile interfaces.


ph7_vm_config

int ph7_vm_config(ph7_vm *pVm,int iConfigOp,...);

Configure a PH7 Virtual machine.

Description

This routine is used to configure a PH7 virtual machine obtained by a prior successful call to one of the compile interface such as ph7_compile()ph7_compile_v2() or ph7_compile_file().

The second argument to ph7_vm_config() is an integer configuration option that determines what property of the PH7 virtual machine is to be configured. Subsequent arguments vary depending on the configuration option in the second argument. There are many verbs but the most important are PH7_VM_CONFIG_OUTPUT, PH7_VM_CONFIG_HTTP_REQUEST and PH7_VM_CONFIG_ARGV_ENTRY. Here is the list of allowed verbs


Configuration Verb

Expected Arguments

Description

PH7_VM_CONFIG_OUTPUT

Two Arguments:

int (*xConsumer)(

  const void *pOutput,

  unsigned int nLen,

  void *pUserData

),

void *pUserData;

This option is used to install a VM output consumer callback. That is, an user defined function responsible of consuming the VM output such as redirecting it (The VM output) to STDOUT or sending it back to the connected peer.

This option accepts two arguments. The first argument is a pointer to the user defined function responsible of consuming the VM output. This callback must accept three arguments. The first argument is a pointer to the VM generated output that the callback body can safely cast to a string (const char *). Note that if the pointer is cast-ed to a string, keep in mind that is not null terminated. The second argument is the VM output length in bytes. The virtual machine guarantee this number is always greater than zero. The last argument is a copy of the pointer (callback private data) passed as the second argument to the this option. When done, the callback must return PH7_OK. But if for some reason the callback wishes to abort processing and thus to stop program execution, it must return PH7_ABORT instead of PH7_OK.

Note that the virtual machine will invoke this callback each time it have something to output.

Refer to the following article for an introduction and some working example of VM output consumer callbacks.

The last argument this option takes is an arbitrary user pointer forwarded verbatim by the engine to the callback as its last argument.

PH7_VM_CONFIG_IMPORT_PATH

One Argument:

const char *zPath;

This option add a path to the import search directories. That is, if a local file is included from the running script using the include, include_once, require or require_once language constructs, then the given path is used as one of the search directory. This option takes a single argument which is a pointer to a NULL terminated string holding the search path.

Example:

/* Import from local/include*/

ph7_vm_config(

pVm,

PH7_VM_CONFIG_IMPORT_PATH,

"/usr/local/include"

);


PH7_VM_CONFIG_ERR_REPORT

No Arguments

This option takes no arguments and if set, all run-time errors such as call to an undefined function, instantiation of an undefined class and so on are reported in the VM output.

PH7_VM_CONFIG_RECURSION_DEPTH

One Argument:

int nMaxDepth

This option is used to set a recursion limit to the running script. That is, a function may not call itself (recurse) more than this limit. If this limit is reached then the virtual machine abort the call and null is returned to the caller instead of the function return value. Note that passing this limit will not stop program execution, simply a null value is returned instead.

The default limit (depending on the host environment) is adequate for most situations (PH7 is smart enough to peek the appropriate value) and thus we recommend the users to not set a limit of their own unless they know what they are doing.

This option accept a single argument which is an integer between 0 and 1024 specifying the desired recursion limit.

PH7_VM_OUTPUT_LENGTH

One Argument:

unsigned int *pLength


This option takes a single argument which is the address of an unsigned integer. The value of this integer will hold the total number of bytes that have been outputted by the Virtual Machine during program execution.

PH7_VM_CONFIG_CREATE_SUPER

Two Arguments:

const char zName,

ph7_value *pValue

This option is used to register a superglobal variable with the running PHP script. This option is useful if you want to pass information from the outside environment to the target PH7 script such as your application name, version, copyright or some environments variables and so forth.

This option accepts two arguments. The first argument is a pointer to a null terminated string holding the name (without the dollar sign) of the super-global to install such as APP_NAME, APP_VERSION and the second argument is a pointer to a ph7_value obtained by a prior successful call to ph7_new_scalar() or ph7_new_array().

Use the following interfaces to populate the ph7_value with the desired value:

ph7_value_int()

ph7_value_int64()

ph7_value_bool()

ph7_value_null()

ph7_value_double()

ph7_value_string()

ph7_value_string_format()

ph7_value_resource()

After installing the super-global, it is recommended that your release its associated value using the ph7_release_value() interface since PH7 will make a private copy of the installed value.

PH7_VM_CONFIG_CREATE_VAR

Two Arguments:

const char zName,

ph7_value *pValue

This option is identical to the PH7_VM_CONFIG_CREATE_SUPER option (accept the same number and types of arguments) except that is used to install a global variable rather than a super-global variable.

PH7_VM_CONFIG_HTTP_REQUEST

Two Arguments:

const char *zRequest,

int nByte

This option is used to pass HTTP request information to the target PHP script. PH7 is shipped with a powerful HTTP request parser and a query decoder for GET, POST and PUT methods. All you have to do is read the raw HTTP request using the standard system call such read() or recv() and pass a pointer to the buffer used for reading the request to this interface and let PH7 parse the request, decode the queries and fill the appropriate arrays such as $_GET, $_POST, $_REQUEST, $_SERVER, etc.

This option must be called prior to program execution so that the PH7 engine can populate the appropriate arrays.

This option accept two arguments. The first argument is a pointer to the raw HTP request just read and 

the second argument is the HTTP request length (data just read) in bytes.

You can refer to the following article for an introduction on how to integrate PH7 in web applications (including servers) that deal with the HTTP protocol.

PH7_VM_CONFIG_SERVER_ATTR

Three Arguments:

const char *zKey,

const char *zValue,

int nLen


This option is used to manually populate the $_SERVER super-global array which hold sever environments entries. This option takes three arguments. The first argument is a pointer to a null terminated string holding the entry key, the second argument is a pointer to a string holding the entry value (This string may not be null terminated). The third argument is the zValue length in bytes. If the nLen argument is less than zero, then zValue is read up to the first zero terminator. If nLen is non-negative, then it is the maximum number of bytes read from zValue.

Example:

ph7_vm_config(

pVm,

PH7_VM_CONFIG_SERVER_ATTR,

"HTTP_CONNECTION",

"Keep-Alive",

-1

);

ph7_vm_config(

pVm,

PH7_VM_CONFIG_SERVER_ATTR,

"HTTP_HOST",

"localhost",

9

);

Now $_SERVER['HTTP_CONNECTION] ==> 'Keep-Alive'

and

$_SERVER['HTTP_HOST'] ==> 'localhost'

PH7_VM_CONFIG_ENV_ATTR

Three Arguments:

const char *zKey,

const char *zValue,

int nLen

This option is used to manually populate the $_ENV super-global array which hold environments variable. This option takes three arguments. The first argument is a pointer to a null terminated string holding the entry key, the second argument is a pointer to a string holding the entry value (This string may not be null terminated). The third argument is the zValue length in bytes. If the nLen argument is less than zero, then zValue is read up to the first zero terminator. If nLen is non-negative, then it is the maximum number of bytes read from zValue.

PH7_VM_CONFIG_SESSION_ATTR

Three Arguments:

const char *zKey,

const char *zValue,

int nLen

This option is used to manually populate the $_SESSION super-global array. This option takes three arguments. The first argument is a pointer to a null terminated string holding the entry key, the second argument is a pointer to a string holding the entry value (This string may not be null terminated). The third argument is the zValue length in bytes. If the nLen argument is less than zero, then zValue is read up to the first zero terminator. If nLen is non-negative, then it is the maximum number of bytes read from zValue.

PH7_VM_CONFIG_POST_ATTR

Three Arguments:

const char *zKey,

const char *zValue,

int nLen

This option is used to manually populate the $_POST super-global array which hold HTTP POST request queries. This option takes three arguments. The first argument is a pointer to a null terminated string holding the entry key, the second argument is a pointer to a string holding the entry value (This string may not be null terminated). The third argument is the zValue length in bytes. If the nLen argument is less than zero, then zValue is read up to the first zero terminator. If nLen is non-negative, then it is the maximum number of bytes read from zValue.

PH7_VM_CONFIG_GET_ATTR

Three Arguments:

const char *zKey,

const char *zValue,

int nLen

This option is used to populate the $_GET super-global array which hold HTTP GET request queries. This option takes three arguments. The first argument is a pointer to a null terminated string holding the entry key, the second argument is a pointer to a string holding the entry value (This string may not be null terminated). The third argument is the zValue length in bytes. If the nLen argument is less than zero, then zValue is read up to the first zero terminator. If nLen is non-negative, then it is the maximum number of bytes read from zValue.

PH7_VM_CONFIG_COOKIE_ATTR

Three Arguments:

const char *zKey,

const char *zValue,

int nLen

This option is used to manually populate the $_COOKIE super-global array which hold HTTP Cookie header values. This option takes three arguments. The first argument is a pointer to a null terminated string holding the entry key, the second argument is a pointer to a string holding the entry value (This string may not be null terminated). The third arguments is the zValue length in bytes. If the nLen argument is less than zero, then zValue is read up to the first zero terminator. If nLen is non-negative, then it is the maximum number of bytes read from zValue.

PH7_VM_CONFIG_HEADER_ATTR

Three Arguments:

const char *zKey,

const char *zValue,

int nLen

This option is used to manually populate the $_HEADER super-global array which hold HTTP MIME headers and their associated values. This option takes three arguments. The first argument is a pointer to a null terminated string holding the entry key, the second argument is a pointer to a string holding the entry value (This string may not be null terminated). The third argument is the zValue length in bytes. If the nLen argument is less than zero, then zValue is read up to the first zero terminator. If nLen is non-negative, then it is the maximum number of bytes read from zValue.

PH7_VM_CONFIG_EXEC_VALUE

One Argument:

ph7_value **ppValue

This option takes one argument which is the address of a pointer to a ph7_value. This will point to the return value of the running script (usually NULL).

PH7_VM_CONFIG_IO_STREAM

One Argument:

const ph7_io_stream *pStream


This option takes a single argument which is a pointer to an instance of the ph7_io_stream structure. A pointer to this instance will be stored in an internal container of the underlying virtual machine so that the scheme associated with this IO stream (I.e: file://, http://, etc.) can be invoked from fopen(), fread(), frwite(), etc. calls. Note that PH7 will not make a private copy of the content of the ph7_io_stream structure which mean that this instance must be available during the life of the library.

You can refer to this page for an introduction to the PH7 IO streams.

PH7_VM_CONFIG_ARGV_ENTRY

One Argument:

const char *zArgValue;

This option is used to populate the $argv global array. The only argument this option takes is a pointer to a null terminated string holding the script argument value to insert.

Example:

ph7_vm_config(

pVm,

PH7_VM_CONFIG_ARGV_ENTRY,

"arg1"

);

ph7_vm_config(

pVm,

PH7_VM_CONFIG_ARGV_ENTRY,

"arg2"

);

Now, $argv[0] value is “arg1” and $argv[1] value is “arg2”


PH7_VM_CONFIG_EXTRACT_OUTPUT

Two Arguments:

const void **ppOut, unsigned int *pLen;

If the host application did not install a VM output consumer callback (This can be done via PH7_VM_CONFIG_OUTPUT), then the Virtual Machine will automatically redirect its output to an internal buffer. This option can be used to point to that buffer.

The first argument this option takes is the address of a void pointer. This pointer will be automatically set by the VM to point to the internal output buffer which is not null terminated.

The second argument is the address of an unsigned integer. This integer will hold the length of the VM output buffer. This option must be called after successful call to ph7_vm_exec() and before ph7_vm_reset() or ph7_vm_release()

Example:

/* Execute the script */

rc = ph7_vm_exec(pVm,0);

if( rc != PH7_OK ){

Fatal("VM execution error");

}

{

const void *pOut;

unsigned int nLen;

/* Extract the output */

ph7_vm_config(

pVm,

PH7_VM_CONFIG_EXTRACT_OUTPUT,

&pOut,

&nLen

);

if( nLen > 0 ){

  /* Redirect to STDOUT */

  printf("%.*s",

      (int)nLen,

      (const char *)pOut /* Not NULL terminated */

   );

  }

}

ph7_vm_reset(pVm);

Note that for performance reason it's preferable to install a VM output consumer callback via (PH7_VM_CONFIG_OUTPUT) rather than waiting for the VM to finish executing and extracting the output.

PH7_VM_CONFIG_ERR_LOG_HANDLER

One Argument:

void (*ProcErrLog)(

const char *zMessage,

int iMsgType,

const char *zDest,

const char *zHeader

)




This option is used to install a error_log() handler. That is, an user defined routine which is invoked each time the running PHP script call the built-in error_log() function.

The callback is responsible of consuming the error message such as sending it to the system logger (I.e: using the syslog() facility) or simply redirecting it to its standard output (STDOUT) and so on.

This option accept a single argument which is a pointer to an user defined function. The callback must accept four arguments. The first argument is a pointer to a null terminated string holding the error message that should be logged. The second argument is an integer between 0 and 4 (Refer to the error_log() PHP manual for more information). The third and fourth arguments are a pointer to a null terminated string holding the destination and extra headers (if available).

Again, refer to the error_log() PHP manual for more information.



Parameters

pVm

A pointer to a PH7 Virtual Machine.

nConfigOp

An integer configuration option that determines what property of the PH7 virtual machine is to be configured.

Return value

PH7_OK is returned on success. Any other return value typically PH7_CORRUPT (Unknown configuration verb) indicates failure.


ph7_vm_exec

int ph7_vm_exec(ph7_vm *pVm,int *pExitStatus);

Execute a compiled PHP program.

Description

This routine is used to execute PH7 bytecode program resulting from successful compilation of the target PHP script using one of the compile interfaces such as ph7_compile(), ph7_compile_v2() or ph7_compile_file(). If no output consumer callback were installed, then the virtual machine will automatically redirect its output to an internal buffer. The caller can point to that buffer later when the VM have finished executing the program via a call to ph7_vm_config() with a configuration verb set to PH7_VM_CONFIG_EXTRACT_OUTPUT. But remember for performance reason it is preferable to install a VM output consumer callback rather than waiting for the VM to finish executing and extracting the output.

Parameters

pVm

A pointer to a PH7 Virtual Machine.

pExitStaus

Optional: If the caller is interested in extracting the exit status of the program then this integer will hold the exit status number (typically zero). Otherwise pass a NULL pointer.

Return value

PH7_OK is returned on success. Any other return value indicates failure.

Example

Download this C file for a smart introduction to this interface.


ph7_vm_reset

int ph7_vm_reset(ph7_vm *pVm);

Reset a PH7 Virtual machine to its initial state.

Description

This routine is used to reset the Virtual Machine to its initial state so that the caller can safely recall ph7_vm_exec() and execute the compiled program again.

Parameters

pVm

A pointer to a PH7 Virtual Machine.

Return value

PH7_OK is returned on success. Any other return value typically PH7_CORRUPT indicates failure.


ph7_vm_release

int ph7_vm_release(ph7_vm *pVm);

Destroy a PH7 Virtual machine.

Description

This routine destroy a working PH7 virtual machine. Every virtual machine must be destroyed using a call to this routine in order to avoid memory leaks.

Parameters

pVm

A pointer to a PH7 Virtual Machine.

Return value

PH7_OK is returned on success. Any other return value typically PH7_CORRUPT indicates failure.


ph7_vm_dump_v2

int ph7_vm_dump_v2(

    ph7_vm *pVm,

    int (*xConsumer)(const void *pDump,unsigned int nLen,void *pUserData),

    void *pUserData

);

Dump PH7 Virtual machine instructions.

Description

This routine is used to dump PH7 bytecode instructions to a human readable format. The dump is redirected to the given consumer callback which is responsible of consuming the generated dump perhaps redirecting it to its standard output (STDOUT).

Parameter

pVm

A pointer to a PH7 Virtual Machine.

int (*xConsumer)(const void *,unsigned int,void *)

Dump consumer callback. The callback must accept three parameters. The first parameter is the generated dump which is not null terminated and the callback body can safely cast to a string (const char *), the second parameter is the dump length in bytes (The engine guarantee this number is always greater than zero) and the last parameter is the callback private data (arbitrary user pointer forwarded verbatim by the engine).

The callback must return PH7_OK. Otherwise the dump generation is aborted immediately.

pUserData

An arbitrary user pointer forwarded verbatim by the engine to the callback as its third argument.

Return value

PH7_OK is returned on success. Any other return value indicates failure.


ph7_create_function

int ph7_create_function(

    ph7_vm *pVm,

    const char *zName,

    int (*xFunc)(ph7_context *pCtx,int argc,ph7_value **argv),

    void *pUserData

);

Install a foreign function and call it from your PHP code.

Description

This interface known as "foreign function creation routine" is used to add PHP functions or to redefine the behavior of existing PHP functions. After successful call to this interface, the installed function is available immediately and can be called from the target PHP code.


The first parameter is the virtual machine to which the PHP function is to be added. If an application uses more than one virtual machine then application-defined PHP functions must be added to each virtual machine separately.

The second parameter is a pointer to a null terminated string holding the name of the PHP function to be created or redefined. A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. Also note that functions names under PH7 are case-sensitive unlike the standard PHP engine.


The third and most important parameter is a pointer to C-language function that implement the PHP function. This function must accept three parameters. The first parameter is a pointer to a ph7_context structure. This is the context in which the foreign function executes. In other words, this parameter is the intermediate between the foreign function and the underlying virtual machine.


The application-defined foreign function implementation will pass this pointer through into calls to dozens of interfaces, these includes:

ph7_context_output(), ph7_context_throw_error(), ph7_context_new_scalar(), ph7_context_user_data(), ph7_context_alloc_chunk() and many more.

The computation result (i.e: the return value) of the foreign function can be set via one of these interfaces:


ph7_result_int()

ph7_result_int64()

ph7_result_bool()

ph7_result_double()

ph7_result_null()

ph7_result_string()

ph7_result_value()

ph7_result_resource()

ph7_result_string_format()


If no call is made to one of these interfaces, then a NULL return value is assumed.


The second parameter xFunc() takes is the total number of arguments passed to the foreign function. If the total number of arguments is not the expected one, the foreign functions can throw an error via ph7_context_throw_error() as follow:

ph7_context_throw_error(pCtx,PH7_CTX_WARNING,"Unexpected number of arguments");


The last parameter xFunc() takes is an array of pointers to ph7_value which represents function arguments. The implementation of the foreign functions can extract their contents via one of these interfaces:


ph7_value_to_int()

ph7_value_to_bool()

ph7_value_to_int64()

ph7_value_to_double()

ph7_value_to_string()

ph7_value_to_resource()

ph7_value_compare()


The xFunc() implementation must return PH7_OK on success, but if the callbacks wishes to abort processing (to stop program execution) and thus to emulate the exit() or die() PHP language constructs, it must return PH7_ABORT instead.

The fourth and last parameter to ph7_create_function() is an arbitrary pointer. The implementation of the function can gain access to this pointer using ph7_context_user_data(). Also note that foreign functions can store an arbitrary number of auxiliary private data in a stack-able manner via ph7_context_push_aux_data().


Built-in functions may be overloaded by new application-defined functions. Note that PH7 come with more than 460 built-in functions installed using this interface.

This function must be called before program execution via ph7_vm_exec().

You can refer to the following guide for an introductory course to this interface and the foreign function mechanism in general.

Parameters

pVm

A pointer to a PH7 Virtual Machine.

zName

A pointer to a null terminated string holding the name of the foreign function.

xFunc

A pointer to a C function performing the desired computation.

pUserData

Arbitrary user pointer that can be extracted later in the implementation of the foreign function via a call to ph7_context_user_data().

Return value

PH7_OK is returned on success. Any other return value typically (PH7_NOMEM) indicates failure.

Example

Download this C file for a smart introduction to this interface.


ph7_delete_function

int ph7_delete_function(ph7_vm *pVm,const char *zName);

Delete a foreign function.

Description

This routine deletes an installed foreign function. That is, any future invocation of the function will throw a call to an undefined function error.

Parameters

pVm

A pointer to a PH7 Virtual Machine.

zName

A pointer to a null terminated string holding the name of the foreign function to be deleted.

Return value

PH7_OK is returned on success. Any other return value indicates failure (no such function).


ph7_create_constant

int ph7_create_constant(

    ph7_vm *pVm,

    const char *zName,

    void (*xExpand)(ph7_value *pValue,void *pUserData),

    void *pUserData

);

Constant Expansion Mechanism: Expand a constant to the desired value via user installable callbacks.

Description

This routine is used to register constants which are expanded to the desired value when invoked later from the running PHP script.


The constant expansion mechanism under PH7 is extremely powerful yet simple and work as follows:

Each registered constant have a C procedure associated with it. This procedure known as the constant expansion callback is responsible of expanding the invoked constant to the desired value. For example the C procedure associated with the “__PI__” constant expands to 3.14 (the value of PI), the “__OS__” constant expands to the name of the host Operating System (Windows, Linux) and so on.

The third and most important parameter this function takes is an application-defined procedure responsible of expanding the constant to the desired value. This procedure must accept two arguments. The first argument is a pointer to a ph7_value that the procedure must fill with the desired value for example 3.14 (value of PI) is stored in this pointer. Use the following interfaces to populate the ph7_value with the desired value:


ph7_value_int()

ph7_value_int64()

ph7_value_bool()

ph7_value_null()

ph7_value_double()

ph7_value_string()

ph7_value_string_format()

ph7_value_resource()


The second argument is a copy of the fourth argument to this function which is forwarded verbatim by engine.

Built-in constants may be overloaded by new application-defined constants. Note that PH7 come with more than 200 built-in constants installed using this interface.


A valid constant name starts with a letter or underscore, followed by any number of letters, numbers or underscores. Also note that constants names are case-sensitive.


This function must be called before program execution via ph7_vm_exec().

You can refer to the following guide for an introductory course to this interface and the constant expansion mechanism in general.

Parameters

pVm

A pointer to a PH7 Virtual Machine.

zName

A pointer to a null terminated string holding the name of the constant to expand for example __PI__, __OS__, PHP_EOL.

xExpand

Host-application defined procedure responsible of expanding the constant to the desired value.

pUserData

Arbitrary user pointer which is forwarded verbatim by the engine to the callback as its second argument.

Return value

PH7_OK is returned on success. Any other return value typically (PH7_NOMEM) indicates failure.

Example

Download this C file for a smart introduction to this interface.


ph7_delete_constant

int ph7_delete_constant(ph7_vm *pVm,const char *zName);

Delete a constant.

Description

This routine remove an installed constant from the constants table.

Parameters

pVm

A pointer to a PH7 Virtual Machine.

zName

A pointer to a null terminated string holding the name of the constant to be deleted.

Return value

PH7_OK is returned on success. Any other return value indicates failure (no such constant).


Foreign Function Parameter Values

int ph7_value_to_int(ph7_value *pValue);

int ph7_value_to_bool(ph7_value *pValue);

ph7_int64 ph7_value_to_int64(ph7_value *pValue);

double ph7_value_to_double(ph7_value *pValue);

const char * ph7_value_to_string(ph7_value *pValue,int *pLen);

void * ph7_value_to_resource(ph7_value *pValue);

int ph7_value_compare(ph7_value *pLeft,ph7_value *pRight,int bStrict);


Obtaining foreign function parameter values.

Description

The C-language implementation of PHP functions uses this set of interface routines to access the parameter values on the function. The xFunc parameter to ph7_create_function() define callbacks that implement the PHP functions. The 3rd parameter to these callbacks is an array of pointers to ph7_value objects. There is one ph7_value object for each parameter to the foreign PHP function. These routines are used to extract values from the ph7_value objects. Please note that if the ph7_value is not of the expected type, an automatic cast will be performed.


The ph7_value_to_string() function takes an optional parameter (int *pLen) which is set (if not NULL) to the string length. Also note, this function return a null terminated string and does never return the NULL pointer.

Please pay particular attention to the fact that the pointer returned from ph7_value_to_string() can be invalidated by subsequent call to ph7_value_to_int(), ph7_value_to_bool(), ph7_value_to_int64() or ph7_value_to_double().

The ph7_value_to_resource() interface will return NULL if the given ph7_value is not of type resource.

The ph7_value_compare() interface is used to compare two ph7_value's. The return value will be 0 (zero) if the values are equals, >0 if the left (first argument) value is greater than the right (second argument) and <0 if the left (first argument) value is less than the right (second argument).


These routines must be called from the same thread as the foreign function that supplied the ph7_value parameters.

Parameters

pValue

A pointer to a ph7_value.

Return value

Value of the given parameter.

Example

Download this C file for a smart introduction to these interfaces.


Dynamically Typed Value Object Management Interfaces

int ph7_value_is_int(ph7_value *pVal);

int ph7_value_is_float(ph7_value *pVal);

int ph7_value_is_bool(ph7_value *pVal);

int ph7_value_is_string(ph7_value *pVal);

int ph7_value_is_null(ph7_value *pVal);

int ph7_value_is_numeric(ph7_value *pVal);

int ph7_value_is_callable(ph7_value *pVal);

int ph7_value_is_scalar(ph7_value *pVal);

int ph7_value_is_array(ph7_value *pVal);

int ph7_value_is_object(ph7_value *pVal);

int ph7_value_is_resource(ph7_value *pVal);

int ph7_value_is_empty(ph7_value *pVal);


Check if the given ph7_value is of the expected type.

Description

As their name suggests, these routines returns TRUE if the given ph7_value is of the expected type as requested by the caller. For example ph7_value_is_int() return TRUE only if the given ph7_value is of type integer, ph7_value_is_string() return TRUE only if the given ph7_value is of type string and so on.

Note that these routines does not perform any automatic conversion when checking ph7_value type. If such behavior is wanted, please use ph7_value_to_string() ph7_value_to_int(), etc. instead.

These routines are useful inside foreign functions to make sure that the given arguments are of the expected type.

The ph7_value_is_callable() interface does not check for a type but instead check if the given ph7_value is a callback. That is, a function that can be called from the target PHP code.

Parameters

pValue

A pointer to a ph7_value.

Return value

These routines returns 1 (TRUE) if the given ph7_value is of the expected type. 0 (zero) (FALSE) otherwise.

Example

Download this C file for a smart introduction to these interfaces.


Populating Dynamically Typed Value Object

int ph7_value_int(ph7_value *pVal,int iValue);

int ph7_value_int64(ph7_value *pVal,ph7_int64 iValue);

int ph7_value_bool(ph7_value *pVal,int iBool);

int ph7_value_null(ph7_value *pVal);

int ph7_value_double(ph7_value *pVal,double Value);

int ph7_value_string(ph7_value *pVal,const char *zString,int nLen);

int ph7_value_string_format(ph7_value *pVal,const char *zFormat,...);

int ph7_value_reset_string_cursor(ph7_value *pVal);

int ph7_value_resource(ph7_value *pVal,void *pUserData);


Populate a ph7_value with the desired value.

Description

These routines are used to populate a freshly created ph7_value obtained by a prior successful call to ph7_context_new_scalar() or from a callback responsible of expanding constant value.


The ph7_value_int() interface sets the ph7_value to the integer type where the value is specified by its 2nd argument.

The ph7_value_int64() interface sets the ph7_value to the 64-bit integer type where the value is specified by its 2nd argument.

The ph7_value_double() interface sets the ph7_value to the float type where the value is specified by its 2nd argument.

The ph7_value_bool() interface sets the ph7_value to the Boolean type where the value (Only zero is assumed FALSE) is specified by its 2nd argument.

The ph7_value_null() interface sets the ph7_value to the NULL type.

The ph7_value_resource() interface sets the ph7_value to the resource type where the value is specified by its 2nd argument which is an arbitrary user pointer that can be extracted later using ph7_value_to_resource().

The ph7_value_string() interface sets the ph7_value to the string type where the string content is specified by the 2nd argument.

Note that ph7_value_string() accepts a third argument which is the length of the string to append. If the nLen argument is less than zero, then zString is read up to the first zero terminator. If nLen is non-negative, then it is the maximum number of bytes read from zString.

ph7_value_string_format() is a work-alike of the "printf()" family of functions from the standard C library which is used to append a formatted string.

The ph7_value_string() and ph7_value_string_format() interfaces write their result to an internal buffer that grow automatically by successive calls to one of them (An append operation). That is, previously written data is not erased by the new call. If such behavior is wanted, call ph7_value_reset_string_cursor() to reset the internal buffer.


Example

ph7_value_string(pValue,"Welcome, current time is: ",-1);

            ph7_value_string_format(pValue,"%02d:%02d:%02d",14,12,59);

The final result if extracted by ph7_value_to_string() would look like this:

Welcome, current time is: 14:12:59”


These routines are very useful when implementing foreign functions that need to populate arrays values.

If these routines are called from within the different thread than the one containing the application-defined function that received the ph7_value pointer, the results are undefined.

Parameters

pValue

A pointer to a ph7_value to populate.

Return value

PH7_OK is returned on success. Any other return value indicates failure.

Example

Download this C file for a smart introduction to these interfaces.


Setting The Result Of A Foreign Function

int ph7_result_int(ph7_context *pCtx,int iValue);

int ph7_result_int64(ph7_context *pCtx,ph7_int64 iValue);

int ph7_result_bool(ph7_context *pCtx,int iBool);

int ph7_result_double(ph7_context *pCtx,double Value);

int ph7_result_null(ph7_context *pCtx);

int ph7_result_string(ph7_context *pCtx,const char *zString,int nLen);

int ph7_result_string_format(ph7_context *pCtx,const char *zFormat,...);

int ph7_result_value(ph7_context *pCtx,ph7_value *pValue);

int ph7_result_resource(ph7_context *pCtx,void *pUserData);

Set the return value of a foreign function.

Description

These routines are used by the xFunc() callback that implement foreign PHP functions to return their computation result. See ph7_create_function() for additional information.

These functions work very much like the ph7_value_* family of functions used to populate ph7 values.


The ph7_result_int() interface sets the result from an application-defined function to be an integer value specified by its 2nd argument.

The ph7_result_int64() interface sets the result from an application-defined function to be a 64-bit integer value specified by its 2nd argument.

The ph7_result_double() interface sets the result from an application-defined function to be a floating point value specified by its 2nd argument.

The ph7_result_bool() interface sets the result from an application-defined function to be a Boolean value (Only zero is assumed FALSE) specified by its 2nd argument.

The ph7_result_null() interface sets the return value of the application-defined function to be NULL (default return value).

The ph7_result_resource() interface sets the result from an application-defined function to be a resource value specified by its 2nd argument which is an arbitrary user pointer that can be extracted later using ph7_value_to_resource(). (This is how the built-in XML parser is implemented).

The ph7_result_value() interface sets the result from an application-defined function to be a copy of the ph7_value obtained by a prior successful call to ph7_context_new_scalar() or ph7_context_new_array(). This is how arrays are returned (Download this C file for a working example).

The ph7_result_string() interface sets the result from an application-defined function to be a string value whose content is specified by the 2nd argument.

Note that ph7_result_string() accepts a third argument which is the length of the string to append. If the nLen argument is less than zero, then zString is read up to the first zero terminator. If nLen is non-negative, then it is the maximum number of bytes read from zString.

ph7_result_string_format() is a work-alike of the "printf()" family of functions from the standard C library which is used to append a formatted string.

Note that the printf() implementation in the PH7 engine is based on the one found in the SQLite3 source tree.

The ph7_result_string() and ph7_result_string_format() interfaces write their result to an internal buffer that grow automatically by successive calls to one of them (An append operation). That is, previously written data is not erased by the new call.


Example

ph7_result_string(pCtx,"Welcome, current time is: ",-1);

  ph7_result_string_format(pCtx,"%02d:%02d:%02d",14,12,59);

The final return value of the foreign functions would look like this:

Welcome, current time is: 14:12:59”


If these routines are called from within the different thread than the one containing the application-defined function that received the ph7_context pointer, the results are undefined.

You can refer to the following guide for an introductory course to this interface and the foreign function mechanism in general.

Parameters

pCtx

Foreign function call context.

Return value

PH7_OK is returned on success. Any other return value indicates failure.

Example

Download this C file for a smart introduction to these interfaces.


ph7_context_output

int ph7_context_output(ph7_context *pCtx,const char *zString,int nLen);

int ph7_context_output_format(ph7_context *pCtx,const char *zFormat,...);

Output a message.

Description

These routines when invoked redirects the desired message to output to the VM Output Consumer Callback. That is, these routines emulate the echo PHP language construct inside foreign functions.

Note that ph7_context_output() accepts a third argument which is the length of the string to output. If the nLen argument is less than zero, then zString is read up to the first zero terminator. If nLen is non-negative, then it is the maximum number of bytes read from zString.

ph7_context_output_format() is a work-alike of the "printf()" family of functions from the standard C library which is used to output a formatted string.

These routines accepts as their first arguments a pointer to a ph7_context which mean that they are designed to be invoked only from a foreign function.

These routines must be called from the same thread in which the application-defined function is running.

Parameters

pCtx

Foreign Function Call Context.

Return value

PH7_OK is returned on success. Any other return value indicates failure.

Example

Download this C file for a smart introduction to these interfaces.


ph7_context_throw_error

int ph7_context_throw_error(ph7_context *pCtx,int iErr,const char *zErr);

int ph7_context_throw_error_format(ph7_context *pCtx,int iErr,const char *zFormat,...);

Throw an error message inside a foreign function.

Description

These routines when invoked throw an error message to the installed VM Output Consumer Callback. That is, these routines emulate the trigger_error() PHP function inside foreign functions.

Note that the underlying Virtual Machine continues its execution normally when an error is thrown. If the caller want to stop program execution and thus to emulate the die() PHP language construct inside a foreign function, simply return PH7_ABORT instead of PH7_OK;

Note that ph7_context_throw_error() accepts a third argument which is the length of the string to output. If the nLen argument is less than zero, then zString is read up to the first zero terminator. If nLen is non-negative, then it is the maximum number of bytes read from zString.

ph7_context_throw_error_format() is a work-alike of the "printf()" family of functions from the standard C library which is used to output a formatted string.

These routines accepts as their first arguments a pointer to a ph7_context which mean that they are designed to be invoked only from a foreign function.

These routines must be called from the same thread in which the application-defined function is running.

Parameters

pCtx

Foreign Function Call Context.

iErr

Error message severity level. This can be one of the following constants (Not a combination):

PH7_CTX_ERR

Call context error such as unexpected number of arguments, invalid types and so on.

PH7_CTX_WARNING

Call context warning.

PH7_CTX_NOTICE

Call context notice.

Return value

PH7_OK is returned on success. Any other return value indicates failure.

Example

Download this C file for a smart introduction to these interfaces.


On demand ph7_value allocation

ph7_value * ph7_context_new_scalar(ph7_context *pCtx);

ph7_value * ph7_context_new_array(ph7_context *pCtx);

void ph7_context_release_value(ph7_context *pCtx,ph7_value *pValue);

ph7_value * ph7_new_scalar(ph7_vm *pVm);

ph7_value * ph7_new_array(ph7_vm *pVm);

int ph7_release_value(ph7_vm *pVm,ph7_value *pValue);

Allocate ph7_value on demand.

Description

These routine allocate ph7_value on demand, they are used mostly by foreign functions that populate and returns arrays.

ph7_context_new_scalar() allocate a new scalar ph7_value which is set to the null type by default. Use the following interfaces to populate the ph7_value with the desired value:


ph7_value_int()

ph7_value_int64()

ph7_value_bool()

ph7_value_null()

ph7_value_double()

ph7_value_string()

ph7_value_string_format()

ph7_value_resource()


ph7_context_new_array() allocate a new ph7_value of type array. The array can be populated later using one of these interfaces ph7_array_add_elem(), ph7_array_add_strkey_elem() and ph7_array_add_intkey_elem().

Note that if you want to return the allocated ph7_value, use ph7_result_value().


ph7_context_release_value() destroy a ph7_value obtained by a prior call to ph7_context_new_scalar() or ph7_context_new_array(). Note that this call is not necessary since the garbage collector subsystem will automatically destroy any allocated ph7_value as soon the foreign function have finished its execution.


These routines accepts as their first argument a pointer to a ph7_context which mean that they are designed to be invoked only from a foreign function.


ph7_new_scalar(), ph7_new_array() and ph7_release_value() follows the same semantics as ph7_context_new_scalar(), ph7_context_new_array() and ph7_context_release_value() except that they take as their first parameter a pointer to a ph7_vm instance. They are used for the creation of superglobals that are registered later via ph7_vm_config() with a configuration verb set to PH7_VM_CONFIG_CREATE_SUPER or PH7_VM_CONFIG_CREATE_VAR.

Parameters

pCtx

Foreign Function Call Context.

Return value

ph7_context_new_scalar(), ph7_context_new_array(), ph7_new_scalar() and ph7_new_array() return a pointer to a freshly allocated ph7_value on success. Otherwise NULL is returned on failure (i.e: Out of memory).

ph7_context_release_value() and ph7_release_value() does not return anything.

Example

Download this C file for a smart introduction to these interfaces.


ph7_array_fetch

ph7_value * ph7_array_fetch(ph7_value *pArray,const char *zKey,int nByte);

Extract array entry value.

Description

This routine is used to extract a array entry value where zKey is its key. The ph7_value must be of type array obtained by a prior successful call to ph7_context_new_array() or passed as parameter to the foreign function. Otherwise this routine returns the NULL pointer in case the given ph7_value is not of type array.

If the target array is numerically indexed then you can pass numeric string keys such as “1”, 2”, 750”, etc. PH7 is smart enough to figure out that we are dealing with numeric keys.

If the given key does not refer to a valid entry then this routine return the NULL pointer. Otherwise the entry value is returned on success. This value can be manipulated or modified using one these interfaces and the change is immediately seen in the target array:

ph7_value_int()

ph7_value_int64()

ph7_value_bool()

ph7_value_null()

ph7_value_double()

ph7_value_string()

ph7_value_string_format()

ph7_value_resource()

Parameters

pArray

ph7_value to query which must be of type array.

zKey

Lookup key.

nByte

zkey length. If this argument is less than zero, then zKey is read up to the first zero terminator. If nByte is non-negative, then it is the maximum number of bytes read from zKey.

Return value

If the given key does not refer to a valid array entry or the given ph7_value is not of type array, then this function return the NULL pointer. Otherwise the entry value is returned on success.

Example

Download this C file for a smart introduction to the array handling interfaces.


ph7_array_walk

int ph7_array_walk(

      ph7_value *pArray,

      int (*xWalk)(ph7_value *pKey,ph7_value *pValue,void *pUserData),

     void *pUserData

);

Iterate Over array entries and invoke the supplied callback for each entry.

Description

This routine iterates over array entries and invokes the supplied walker callback for each array entry. The first argument (pArray) must be of type array obtained by a prior successful call to ph7_context_new_array() or passed as parameter to the foreign function. Otherwise, this routine return immediately and the walk process could not be done.

The most interesting parameter this function takes is the walker callback which is an user defined function that is invoked for each array entry. The callback must accept three arguments. The first argument is the entry key which could be any scalar value such an integer, string, double or even the null value.

The second argument is the entry value which could be any type even arrays and the third and last argument is a copy of the third argument to this function which is forwarded verbatim by engine.

The callback must return PH7_OK. Otherwise the walk process is aborted and this function return PH7_ABORT.

The key and entry value could be extracted inside the callback using these interfaces:

ph7_value_to_int()

ph7_value_to_bool()

ph7_value_to_int64()

ph7_value_to_double()

ph7_value_to_string()

ph7_value_to_resource()

ph7_value_compare()

Note that the key and its value are passed to the callback by copy. That is, any subsequent changes to their types or values is not reflected. If you want to modify the entry value use ph7_array_fetch() instead.

Parameters

pArray

ph7_value to walk which must be of type array.

xWalk

Walker callback that is invoked for each array entry. If the callback wishes to abort the walk process, it must return a value different from PH7_OK such as PH7_ABORT.

pUserDara

Arbitrary user pointer which is forwarded verbatim by the engine to the walker callback as its third argument.

Return value

This function return PH7_OK on success. Any other return value indicates failure.

Example

Download this C file for a smart introduction to the array handling interfaces.


ph7_array_add_elem

int ph7_array_add_elem(ph7_value *pArray,ph7_value *pKey,ph7_value *pValue);

int ph7_array_add_strkey_elem(ph7_value *pArray,const char *zKey,ph7_value *pValue);

int ph7_array_add_intkey_elem(ph7_value *pArray,int iKey,ph7_value *pValue);

Populate array values.

Description

These routines populates array values. The given ph7_value (first argument) must be of type array obtained by a prior successful call to ph7_context_new_array() or ph7_new_array(). Otherwise these routines return immediately with an error code.

The second argument to ph7_array_add_elem() is a scalar ph7_value obtained by a prior successful call to ph7_context_new_scalar(), ph7_new_array() or passed as parameter to the foreign function. Note that if you want an automatically assigned key (usually a numeric number), simply pass a NULL pointer.


The third argument to ph7_array_add_elem() is a ph7_value of any type obtained by a prior successful call ph7_context_new_scalar(), ph7_new_scalar(), ph7_context_new_array(), ph7_new_array() or passed as parameter to the foreign function. This is is the entry value that could be extracted later using ph7_array_fetch() or from your PHP code using the standard array access operator ($array['key']). Note that if you want a null entry value, simply pass a NULL pointer.


ph7_array_add_strkey_elem() and ph7_array_add_intkey_elem() are simple wrapper around ph7_array_add_elem(). The first function accepts a null terminated string which is used as the entry key while the second accept a numeric key.

Note that the three interfaces listed above will make their own copy of the key and the value so it is safe to use the same ph7_value for other insertions.

Parameters

pArray

ph7_value to populate which must be of type array.

Return value

PH7_OK is returned on successful insertion. Any other return value typically (PH7_CORRUPT or PH7_NOMEM) indicates failure.

Example

Download this C file for a smart introduction to the array handling interfaces.


ph7_array_count

unsigned int ph7_array_count(ph7_value *pArray);

Return the Total number of inserted entries in a array.

Description

This routine return the total number of inserted entries in a given array. The ph7_value must be of type array obtained by a prior successful call to ph7_context_new_array() or passed as parameter to the foreign function.

Call ph7_value_is_array() to check if the ph7_value is of the expected type.

Parameters

pArray

ph7_value to query which must be of type array.

Return value

This function return the total number of inserted entries on success. 0 (zero) is returned if the array is empty or the given ph7_value is not of type array (a scalar value such as an integer, Boolean, double, etc.).

Example

Download this C file for a smart introduction to the array handling interfaces.


ph7_object_get_class_name

const char * ph7_object_get_class_name(ph7_value *pObject,int *pLength);

Return the class name from which this object was instantiated.

Description

This routine return the name of the class from which this object was instantiated. The ph7_value must be of type object passed as parameter to the foreign function. Otherwise this function return the NULL pointer.

Call ph7_value_is_object() to check if the ph7_value is of the expected type.


Parameters

pObject

ph7_value to query which must be of type object.

Return value

On success, this function return a pointer to a null terminated string holding the name of the class from which this object was instantiated. Otherwise NULL is returned on failure.


ph7_object_fetch_attr

ph7_value * ph7_object_fetch_attr(ph7_value *pObject,const char *zAttr);

Extract object attribute value.

Description

This routine is used to extract object attribute value where zAttr is the attribute name. The ph7_value must be of type object passed as parameter to the foreign function. Otherwise this routine return the NULL pointer in case the given ph7_value is not of type object.

Call ph7_value_is_object() to check if the ph7_value is of the expected type.

If the given key does not refer to a valid attribute name or if the attribute visibility is not public (i.e: private or protected), then this routine return the NULL pointer. Otherwise the attribute value is returned on success. This value could be manipulated or modified using one these interfaces and the change is immediately seen:

ph7_value_int()

ph7_value_int64()

ph7_value_bool()

ph7_value_null()

ph7_value_double()

ph7_value_string()

ph7_value_string_format()

ph7_value_resource()

Parameters

pObject

ph7_value to query which must be of type object.

zAttr

A pointer to a null terminated string holding the attribute name.

Return value

Attribute value is returned on success. Otherwise NULL is returned on failure.


ph7_object_walk

int ph7_object_walk(

    ph7_value *pObject,

    int (*xWalk)(const char *zAttrName,ph7_value *pAttrValue,void *pUserData),

    void *pUserData

);

Iterate over public object attributes and invoke the supplied callback for each attribute.

Description

This routine iterates over public object attributes and invokes the supplied walker xWalk() callback for each attribute. The first argument (pObject) must be of type object passed as parameter to the foreign function. Otherwise, this routine return immediately and the walk process could not be done.

Call ph7_value_is_object() to check if the ph7_value is of the expected type.

The most interested parameter this function takes is the walker callback which is an user defined function that is invoked for each retrieved public attribute. The callback must accept three arguments. The first argument is a pointer to a null terminated string holding the attribute name.

The second argument is the attribute value which could be any type even object.

The third and last argument is a copy of the third argument to this function which is forwarded verbatim by engine.

The callback must return PH7_OK. Otherwise the walk process is aborted and this function return PH7_ABORT.

The attribute value could be extracted inside the callback using these interfaces:

ph7_value_to_int()

ph7_value_to_bool()

ph7_value_to_int64()

ph7_value_to_double()

ph7_value_to_string()

ph7_value_to_resource()

ph7_value_compare()

Note that the attribute value is passed to the callback by copy. That is, any subsequent changes to its type or value is not reflected. If you want to modify the attribute value use ph7_object_fetch_attr() instead.

Parameters

pObject

ph7_value to walk which must be of type object.

xWalk

Walker callback that is invoked for each public object attribute. If the callback wishes to abort the walk process, it must return a value different from PH7_OK such as PH7_ABORT.

pUserDara

Arbitrary user pointer which is forwarded verbatim by the engine to the walker callback as its third argument.

Return value

This function return PH7_OK on success. Any other return value indicates failure.


Call Context Memory Management Interfaces

void * ph7_context_alloc_chunk(ph7_context *pCtx,unsigned int nByte,int ZeroChunk,int AutoRelease);

void * ph7_context_realloc_chunk(ph7_context *pCtx,void *pChunk,unsigned int nByte);

void ph7_context_free_chunk(ph7_context *pCtx,void *pChunk);

Memory Allocation Routines

Description

As their names suggests these interfaces allocate/re-allocate/free memory using the PH7 memory backend subsystem.

These interfaces accepts as their first argument a pointer to a ph7_context which mean that they are designed to be invoked only from a foreign function.


The ph7_context_alloc_chunk() routine returns a pointer to a block of memory at least nByte bytes in length, where nByte is the second parameter. 

The last parameter ph7_context_alloc_chunk() takes is a Boolean flag when set to TRUE (any value different from zero) then the allocated chunk is automatically released upon the foreign function have finished its execution. That is, there is no need to manually call ph7_context_free_chunk().


The ph7_context_realloc_chunk() interface attempts to resize a prior memory allocation to be at least nByte bytes, where nByte is the third parameter. The memory allocation to be resized is the second parameter. If the second parameter to ph7_context_realloc_chunk() is a NULL pointer then its behavior is identical to calling ph7_context_alloc_chunk(nByte) where nByte is the third parameter to ph7_context_realloc_chunk().


Calling ph7_context_free_chunk() with a pointer previously returned by ph7_context_alloc_chunk() or ph7_context_realloc_chunk() releases that memory so that it might be reused. Passing a NULL pointer to ph7_context_free_chunk() is harmless. Note that after being freed, memory should neither be read nor written otherwise the result is undefined

Parameters

pCtx

Foreign function Call Context.

Return value

A pointer to a freshly allocated/re-allocated chunk is returned on success. NULL is returned on failure (an out-of-memory).


ph7_context_user_data

void * ph7_context_user_data(ph7_context *pCtx);

Extract foreign function private data.

Description

The ph7_context_user_data() interface returns a copy of the pointer that was the pUserData parameter (the last parameter) of the ph7_create_function() that originally registered the application defined function.

This routine accepts as its first argument a pointer to a ph7_context which mean that is designed to be invoked only from a foreign function.

This routine must be called from the same thread in which the application-defined function is running.

Parameters

pCtx

Foreign Function Call Context.

Return value

A copy of the pointer untouched.


Stack-able Foreign Function Auxiliary Data

int ph7_context_push_aux_data(ph7_context *pCtx,void *pUserData);

void * ph7_context_peek_aux_data(ph7_context *pCtx);

void * ph7_context_pop_aux_data(ph7_context *pCtx);

Push/Peek/Pop foreign function auxiliary private data.

Description

These interfaces are available to foreign functions in the case they need a stack for an arbitrary number of auxiliary private data perhaps to keep some state information (i.e: the built-in strtok() function rely on these routines heavily).


The ph7_context_push_aux_data() routine pushes an arbitrary pointer in the auxiliary data stack.

The ph7_context_peek_aux_data() routine return the last pushed user pointer in the auxiliary data stack.

The ph7_context_pop_aux_data() pops and returns the last pushed user pointer in the auxiliary data stack.


These interfaces accepts as their first argument a pointer to a ph7_context which mean that they are designed to be invoked only from a foreign function. Also note that each registered foreign function have its own auxiliary data stack.

These routines must be called from the same thread in which the application-defined function is running.

Parameters

pCtx

Foreign Function Call Context.

Return value

ph7_context_push_aux_data() return PH7_OK if the pointer was successfully pushed on the stack. Any other return value indicates failure (Out of memory)

ph7_context_peek_aux_data()/ph7_context_pop_aux_data() return the last pushed user pointer in the auxiliary data stack or NULL if the stack is empty.


ph7_context_result_buf_length

unsigned int ph7_context_result_buf_length(ph7_context *pCtx);

Call context result buffer length.

Description

This routine return the size of the call context result buffer. The size of this buffer depends on the number of successive calls to ph7_result_string() or ph7_result_string_format().

This routine accepts as its first argument a pointer to a ph7_context which mean that is designed to be invoked only from a foreign function.

Parameters

pCtx

Foreign Function Call Context.

Return value

Call context result buffer length in bytes.


ph7_context_random_num/random_string

unsigned int ph7_context_random_num(ph7_context *pCtx);

int ph7_context_random_string(ph7_context *pCtx,char *zBuf,int nBuflen);

Generate random number/string.

Description

PH7 contains a high-quality pseudo-random number generator (PRNG) based on the one found in the SQLite3 library. The PRNG is also used by the built in rand() and rand_str() PHP functions. These interfaces allows host-applications to access the same PRNG for other purposes.

ph7_context_random_num() returns a 32-bit unsigned integer between 0 and 0xFFFFFFFF.

ph7_context_random_string() generate an English based alphabet string of length nBuflen (last argument).

Note that the generated string is not null terminated and the given buffer must be big enough to hold at least 3 bytes.

These interfaces accepts as their first argument a pointer to a ph7_context which mean that they are designed to be invoked only from a foreign function.

These routines must be called from the same thread in which the application-defined function is running.

Parameters

pCtx

Foreign Function Call Context.

Return value

Random generated number/string.


ph7_function_name

const char * ph7_function_name(ph7_context *pCtx);

Return the name of the invoked foreign function.

Description

This routine return the name of the invoked foreign function.

This routine accepts as its first argument a pointer to a ph7_context which mean that is designed to be invoked only from a foreign function.

This routine never fail and always return a pointer to a null terminated string.

Parameters

pCtx

Foreign Function Call Context.

Return value

A pointer to a null terminated string holding the foreign function name.


Global Library Management Interfaces

int ph7_lib_init(void);

int ph7_lib_config(int nConfigOp,...);

int ph7_lib_shutdown(void);

int ph7_lib_is_threadsafe(void);

const char * ph7_lib_version(void);

const char * ph7_lib_signature(void);

const char * ph7_lib_ident(void);

const char * ph7_lib_copyright(void);

Manual Library Management Interfaces.

Description

The ph7_lib_init() routine initializes the PH7 library. The ph7_lib_shutdown() routine deallocates any resources that were allocated by ph7_lib_init(). These routines are designed to aid in process initialization and shutdown on embedded systems. Workstation applications using PH7 normally do not need to invoke either of these routines.

Note that PH7 is a self initializing library and so a manual call to ph7_lib_init() is not needed. That is, the first call to ph7_init() will automatically initialize the library.

A call to ph7_lib_init() is an "effective" call if it is the first time ph7_lib_init() is invoked during the lifetime of the process, or if it is the first time ph7_lib_init() is invoked following a call to ph7_lib_shutdown(). Only an effective call of ph7_lib_init() does any initialization. All other calls are harmless no-ops.

A call to ph7_lib_shutdown() is an "effective" call if it is the first call to ph7_lib_shutdown() since the last ph7_lib_init() . Only an effective call to ph7_lib_shutdown() does any deinitialization. All other valid calls to ph7_lib_shutdown() are harmless no-ops.

The ph7_lib_init() interface is threadsafe, but ph7_lib_shutdown() is not. The ph7_lib_shutdown() interface must only be called from a single thread. This routine will take care of destroying any open PH7 engines handles and their associated active Virtual Machines.

The ph7_lib_config() interface is used to make global configuration changes to PH7 in order to tune PH7 to the specific needs of the application. The default configuration is recommended for most applications and so this routine is usually not necessary. It is provided to support rare applications with unusual needs.

The ph7_lib_config() interface is not threadsafe. The application must insure that no other PH7 interfaces are invoked by other threads while ph7_lib_config() is running. Furthermore, ph7_lib_config() may only be invoked prior to library initialization using ph7_lib_init() or after shutdown by ph7_lib_shutdown(). If ph7_lib_config() is called after ph7_lib_init() and before ph7_lib_shutdown() then it will return PH7_CORRUPT.

The first argument to ph7_lib_config() is an integer configuration option that determines what property of PH7 is to be configured. Subsequent arguments vary depending on the configuration option in the first argument. Here is the list of allowed verbs


Configuration Verb

Expected Arguments

Description

PH7_LIB_CONFIG_USER_MALLOC

One Argument:

const SyMemMethods *pMethods


This option takes a single argument which is a pointer to an instance of the SyMemMethods structure. The argument specifies alternative low-level memory allocation routines to be used in place of the memory allocation routines built into PH7. Note that PH7 will not make a private copy of the content of the SyMemMethods structure which mean that the instance must be available during the life of the library.

PH7_LIB_CONFIG_MEM_ERR_CALLBACK

Two Arguments:

int (*ProcMemError) (void *)

void *pUserData


This option takes two arguments: a pointer to a host-application defined function which is invoked by the engine when running out-of-memory. The callback must take one argument which isan arbitrary user pointer.

The second argument this option takes is the user pointer which is forwarded verbatim by the engine as the first argument to the callback.

If the callback wishes to retry the failed memory allocation process,it must return SXERR_RETRY.

Note that running out-of-memory is an extremely unlikely scenario on modern hardware even on modern embedded system and so this option is not important as it might looks.

PH7_LIB_CONFIG_USER_MUTEX

One Argument:

const SyMutexMethods *pMethods

This option takes a single argument which is a pointer to an instance of the SyMutexMethods structure. The argument specifies alternative low-level mutex routines to be used in place of the mutex routines built into PH7. Note that PH7 will not make a private copy of the content of the SyMutexMethods structure which mean that the instance must be available during the life of the library.

PH7_LIB_CONFIG_THREAD_LEVEL_SINGLE

No Arguments

This option sets the threading mode to Single-thread. In other words, mutexing is disabled and PH7 is put in a mode where it can only be used by a single thread. This option have meaning only if PH7 is compiled with the PH7_ENABLE_THREADS directive enabled.

PH7_LIB_CONFIG_THREAD_LEVEL_MULTI

No Arguments

This option sets the threading mode to Serialized. In other words, all mutexes are enabled including the recursive mutexes on PH7 engine instance and Virtual Machine objects. In this mode (which is the default when PH7 is compiled with PH7_ENABLE_THREADS) the PH7 library will itself serialize access to PH7 engine instance and Virtual Machine so that the application is free to use the same PH7 engine instance or the same Virtual Machine in different threads at the same time. This option have meaning only if PH7 is compiled with the PH7_ENABLE_THREADS directive enabled.

H7_LIB_CONFIG_VFS

One Argument:

const ph7_vfs *pVfs

This option takes a single argument which is a pointer to an instance of the ph7_vfs structure. The argument specifies alternative Virtual File System routines to be used in place of the built-in VFS which is the recommended one for Windows and UNIX systems. Note that PH7 will not make a private copy of the content of the ph7_vfs structure which mean that the instance must be available during the life of the library.


The ph7_lib_is_threadsafe() function returns TRUE (1) if and only if PH7 was compiled with threading support enabled which is not the default behavior.

PH7 can be compiled with threading support enabled only if the PH7_ENABLE_THREADS compile-time directive is defined. Without multi-threading support (default build) it is not safe to use PH7 concurrently from more than one thread.

Enabling mutexes incurs a measurable performance penalty. So if speed is of utmost importance, it makes sense to disable the mutexes.

 ph7_lib_version(), ph7_lib_signature(), ph7_lib_ident() and ph7_lib_copyright() returns a pointer to a null terminated string holding respectively the current version of the PH7 engine, the library signature, the library identification in the symisc source tree and the copyright notice.

Return value

ph7_lib_init(), ph7_lib_shutdown() and ph7_lib_config() returns PH7_OK on success. Any other return value indicates failure.

ph7_lib_version(), ph7_lib_signature(), ph7_lib_ident() and ph7_lib_copyright() never fails and always return a pointer to a null terminated string.





Symisc Systems
Copyright © Symisc Systems