Skip to content

Instantly share code, notes, and snippets.

@acidlemon
Created November 27, 2014 17:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acidlemon/49e55aaede37c18227b7 to your computer and use it in GitHub Desktop.
Save acidlemon/49e55aaede37c18227b7 to your computer and use it in GitHub Desktop.
simple embedded perl in Go
package main
/*
#include <EXTERN.h>
#include <perl.h>
#include <stdio.h>
static PerlInterpreter* perl;
void init_perl() {
// PerlのCランタイムの初期化(全体で1回)
int argc = 0;
char** argv = NULL;
char** env = NULL;
PERL_SYS_INIT3(&argc, &argv, &env);
// Perlインタプリタの初期化
perl = perl_alloc();
PERL_SET_CONTEXT(perl);
perl_construct(perl);
// Perlインタプリタの実行
char empty[16] = "", e[16] = "-e", zero[16] = "0";
char *embedding[] = { empty, e, zero };
perl_parse(perl, NULL, 3, embedding, NULL);
PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
perl_run(perl);
}
void term_perl() {
perl_destruct(perl);
perl_free(perl);
PERL_SYS_TERM();
}
SV* Perl_eval_pv(const char*, int);
// SvIVはマクロでGoから直接使えないのでC関数にする
long Sv2Iv(SV* sv) {
return SvIV(sv);
}
*/
import "C"
import "fmt"
func main() {
// Perlの準備
C.init_perl()
// Perlの文を評価してスカラ値を取得
sval := C.Perl_eval_pv(C.CString("my $powawa = 3; $powawa *= 3"), 1)
fmt.Printf("powawa = %v\n", C.Sv2Iv(sval))
C.term_perl()
}
@acidlemon
Copy link
Author

$ CGO_CFLAGS=`perl -MExtUtils::Embed -e ccopts` \
  CGO_LDFLAGS=`perl -MExtUtils::Embed -e ldopts` \
  go run test.go

で実行すると

powawa = 9

が得られる

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment