DEV Community

Yuki Kimoto
Yuki Kimoto

Posted on

How to use zlib (a C library) from Perl with SPVM

How to use zlib (a C library) from Perl with SPVM.

See an example to bind zlib to SPVM

SPVM provides a way to bind C language libraries and call them from Perl.

When binding C libraries to Perl, you typically write XS, but SPVM offers an alternative approach.

MyZlib.spvm

class MyZlib {
  native static method test : void ($ouf_file : string);
}
Enter fullscreen mode Exit fullscreen mode

MyZlib.c

#include "spvm_native.h"
#include<stdio.h>

#include "zlib.h"

static const char* FILE_NAME = "MyZlib.c";

int32_t SPVM__MyZlib__test(SPVM_ENV* env, SPVM_VALUE* stack) {

  void* obj_out_file = stack[0].oval;

  if (!obj_out_file){
    return env->die(env, stack, "$ouf_file must be defined.", __func__, FILE_NAME, __LINE__);
  }

  const char* out_file = env->get_chars(env, stack, obj_out_file);

  char buf[]="0123456789abcdefghijklmnopqrstuvwxyz\n";
  int cnt = 0;
  gzFile zp;

  zp = gzopen(out_file, "w9");
  if(zp == NULL){
    return env->die(env, stack, "gzopen failed.", "MyZlib.c", __func__, FILE_NAME, __LINE__);
  }

  for(cnt = 0; cnt < 100; cnt++){
    gzputs(zp, buf);
  }

  gzclose(zp);

  return 0;
}

Enter fullscreen mode Exit fullscreen mode

MyZlib.config

use strict;
use warnings;

use SPVM::Builder::Config;

my $config = SPVM::Builder::Config->new_gnu99(file => __FILE__);

$config->add_lib('z');

$config;
Enter fullscreen mode Exit fullscreen mode

zlib.pl

use strict;
use warnings;

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

use SPVM 'MyZlib';

my $out_file = "$ENV{HOME}/tmp/output.gz";

SPVM::MyZlib->test($out_file);
Enter fullscreen mode Exit fullscreen mode

A compressed file "output.gz" will be output.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more