Embed PERL in Kotlin or call PERL from Kotlin in Windows using MSYS2

Submitted by Dickens A S on Thu, 07/15/2021 - 07:01

This article demonstrates how to call PERL from Kotlin using C APIs

PERL is very old platform. But it is still being used in libraries like GIT and firewall and admin software.

If the developer knows how to invoke a PERL function then from a GUI based software the developer can invoke the function.

Below code explains how to do it.

Kotlin Code

package plot

import platform.posix.*
import kotlinx.cinterop.*
import perl.*

fun main(args: Array<String>) {
    memScoped { 
    	val argc = alloc<IntVar>()
        argc.value = args.size
        
        val argv = alloc<CPointerVar<CPointerVar<ByteVar>>>()
        argv.value = args.map { it.cstr.ptr }.toCValues().ptr
        
        val env = alloc<CPointerVar<CPointerVar<ByteVar>>>()
        env.value = arrayOf<String>().map { it.cstr.ptr }.toCValues().ptr
        
        val embedding = alloc<CPointerVar<CPointerVar<ByteVar>>>()
        embedding.value = arrayOf<String>( "", "-e", "0" ).map { it.cstr.ptr }.toCValues().ptr
        
        _PERL_SYS_INIT3 ( argc.value, argv.value, env.value )
        
        my_perl = perl_alloc()
        perl_construct(my_perl)
        setFlags()
        
        
        perl_parse(my_perl, null, 3, embedding.value, null);
        perl_run(my_perl);
        
        Perl_eval_pv(my_perl, '$' + "a = 3;", 1)
        var a = _get_sv("a".cstr)
        
        println("a is: " + a);
        
        Perl_eval_pv(my_perl, "$" + "a **= 2;", 1)
        
        println("$a power 2 is : " + _get_sv("a".cstr) );
        
        perl_destruct(my_perl)
        perl_free(my_perl)
        _PERL_SYS_TERM ()

    }
}

 

C functions in perl.def

static PerlInterpreter *my_perl;

static inline _PERL_SYS_INIT3(int argc, char **argv, char **env) {
	PERL_SYS_INIT3(&argc,&argv,&env);
}

static inline _PERL_SYS_TERM() {
	PERL_SYS_TERM();
}

static inline setFlags() {
	PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
}

static inline _get_sv(char *argv) {
	return SvNV(get_sv(argv, 0));
}

Output

> Task :runDebugExecutableLibgnuplot
a is: 3
3 power 2 is : 9

Variable a declared inside PERL environment as $a=3; and evaluated from Kotlin

Variable multiplied inside PERL environment as $a**=2; and evaluated from Kotlin

Finished!

 

Add new comment