How to Bind C/C++/CUDA Library to SPVM

The advantage of SPVM is that you can easily bind C/C++/CUDA.

Subroutines bound with SPVM can be easily called from Perl.

Before reading this page, you need to understand Native API.

Binding your own C language library

First, let's bind our own C library.

The following source code is the completed source code.

I will explain using this source code.

SPVM Native Example - Bind C Library

Create a C language library for summation and call it from Perl.

# bind_clib.pl
use strict;
use warnings;

use FindBin;
use lib "$FindBin::Bin/lib";

use SPVM 'BindCLib';

my $total = BindCLib->sum([1, 2, 3, 4]);

print "Total: $total\n";

SPVM Subroutine Definition.

# lib/BindCLib.spvm
package BindCLib {
  native sub sum : int ($nums : int[]);
}

Native Config.

# lib/BindCLib.config
use strict;
use warnings;

use SPVM::Builder::Config;
my $bconf = SPVM::Builder::Config->new_c99;

$bconf;

Call C library from C program.

// lib/BindCLib.c
#include "spvm_native.h"

#include "bind_clib.h"

int32_t SPNATIVE__BindCLib__sum(SPVM_ENV* env, SPVM_VALUE* stack) {
  
  void* sv_nums = stack[0].oval;
  
  int32_t length = env->length(env, sv_nums);
  
  int32_t* nums = env->get_elems_int(env, sv_nums);
  
  int32_t total = bind_clib_sum(nums, length);
  
  stack[0].ival = total;
  
  return SPVM_SUCCESS;
}

Notice the line reading the header.

#include "bind_clib.h"

This header is included from "lib/BindCLib.native/include/bind_clib.h". This is pure C header file.

#include <inttypes.h>

int32_t bind_clib_sum(int32_t* nums, int32_t length);

SPVM sets the include directory("BindCLib.native/include") as the default header file read path.

C library source file is "lib/BindCLib.native/src/bind_clib.c". This is pure C source file.

#include "bind_clib.h"

int32_t bind_clib_sum(int32_t* nums, int32_t length) {
  
  int32_t total = 0;
  for (int32_t i = 0; i < length; i++) {
    total += nums[i];
  }
  
  return total;
}

SPVM compiles all source files in the source directory("BindCLib.native/src"). It can contain multiple source files.

How to bind other C Library to SPVM

If you want to know more about the bindings of other C libraries, see the example below.

How to bind C++ Library to SPVM

If you want to know more about the bindings of C++ libraries to SPVM, see the example below.

How to bind CUDA to SPVM

If you want to know more about the bindings of CUDA to SPVM, see the example below.