The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

SPVM::Document::Cookbook - SPVM Tutorial(BETA)

Advanced

Inline native function

If you use __NATIVE__ keyword, you can write program using C language by inline. This is similar with Inline::C, but SPVM implement this feature by default.

  package TestCase::Inline {
    sub sum($num1 : int, $num2 : int) : native int;
  }

  __NATIVE__

  #include <spvm_api.h>

  int32_t SPVM__TestCase__Inline__sum(SPVM_API* api, SPVM_API_VALUE* args) {

    int32_t total = args[0].int_value + args[1].int_value;
    
    return total;
  }

At first, you specify native descripter at SPVM subroutine.

  package TestCase::Inline {
    # native descripter
    sub sum($num1 : int, $num2 : int) : native int;
  }

Next, you write __NATIVE__ keyword.

  __NATIVE__

Next, you write C language. You include spvm_api.h.

  #include <spvm_api.h>

C Function name must be replace : with <_> and add SPVM__ to top of SPVM subroutine name. SPVM subroutine absolute name is TestCase::Inline::sum. C function name is SPVM__TestCase__Inline__sum.

  int32_t SPVM__TestCase__Inline__sum(SPVM_API* api, SPVM_API_VALUE* args) {

    int32_t total = args[0].int_value + args[1].int_value;
    
    return total;
  }

First argument is api. This is the pointer to SPVM_API. Second argument is args. This is array of SPVM_API_VALUE.

SPVM_API_VALUE is union of C language. If you want to get int value, you do the followng.

  args[0].int_value

You can get all type of value by the following member.

  args[0].byte_value
  args[0].short_value
  args[0].int_value
  args[0].long_value
  args[0].float_value
  args[0].double_value
  args[0].object_value

Type of return value is corresponding the folloing type.

  [SPVM]              [C]
  byte                int8_t
  short               int16_t
  int                 int32_t
  long                int64_t
  float               float
  double              double
  [Object value]      SPVM_API_OBJECT*
  

Debug mode

If you want to see Line Number which exception occur, use SPVM::Debug.

  use SPVM::Debug;

Line number which exception occur is printed to exception message.

For example:

  0 division (int / int)
    from TestCase::exception_zero_divide_int() at /home/kimoto/labo/SPVM/t/lib/SPVM/TestCase.spvm line 26