/
perlembed.pod
2140 lines (1489 loc) · 60.7 KB
/
perlembed.pod
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
=encoding euc-jp
=head1 NAME
=begin original
perlembed - how to embed perl in your C program
=end original
perlembed - C プログラムへの Perl の埋め込み方
=head1 DESCRIPTION
=head2 PREAMBLE
=begin original
Do you want to:
=end original
あなたのやりたいことは
=over 5
=item B<Use C from Perl?>
(B<Perl から C を使うことですか?>)
=begin original
Read L<perlxstut>, L<perlxs>, L<h2xs>, L<perlguts>, and L<perlapi>.
=end original
L<perlxstut>, L<perlxs>, L<h2xs>, L<perlguts>, L<perlapi> を
読みましょう。
=item B<Use a Unix program from Perl?>
(B<Perl から UNIX プログラムを使うことですか?>)
=begin original
Read about back-quotes and about C<system> and C<exec> in L<perlfunc>.
=end original
バッククォートに関することと、
L<perlfunc>にあるC<system>、C<exec>に関することを読みましょう。
=item B<Use Perl from Perl?>
(B<Perl から Perl を使うことですか?>)
=begin original
Read about L<perlfunc/do> and L<perlfunc/eval> and L<perlfunc/require>
and L<perlfunc/use>.
=end original
L<perlfunc/do>、 L<perlfunc/eval>、L<perlfunc/require>、
L<perlfunc/use>を読みましょう。
=item B<Use C from C?>
(B<C から C を使うことですか?>)
=begin original
Rethink your design.
=end original
デザインを考え直しましょう。
=item B<Use Perl from C?>
(B<C から Perl を使うことですか?>)
=begin original
Read on...
=end original
読み続けてください…
=back
=head2 ROADMAP
(ロードマップ)
=over 5
=item *
=begin original
Compiling your C program
=end original
C プログラムをコンパイルする
=item *
=begin original
Adding a Perl interpreter to your C program
=end original
C プログラムに Perl インタプリタを追加する
=item *
=begin original
Calling a Perl subroutine from your C program
=end original
C プログラムから Perl サブルーチンを呼び出す
=item *
=begin original
Evaluating a Perl statement from your C program
=end original
C プログラムから Perl の文を評価する
=item *
=begin original
Performing Perl pattern matches and substitutions from your C program
=end original
C プログラムから Perl のパターンマッチングや置換を実行する
=item *
=begin original
Fiddling with the Perl stack from your C program
=end original
C プログラムから Perl のスタックを扱う
=item *
=begin original
Maintaining a persistent interpreter
=end original
永続的(persistent)インタプリタを取り扱う
=item *
=begin original
Maintaining multiple interpreter instances
=end original
複数のインタプリタのインスタンスを取り扱う
=item *
=begin original
Using Perl modules, which themselves use C libraries, from your C program
=end original
C ライブラリを使っている Perl のモジュールを C プログラムから使う
=item *
=begin original
Embedding Perl under Win32
=end original
Win32 における組み込み Perl
=back
=head2 Compiling your C program
(あなたのCプログラムをコンパイルする)
=begin original
If you have trouble compiling the scripts in this documentation,
you're not alone. The cardinal rule: COMPILE THE PROGRAMS IN EXACTLY
THE SAME WAY THAT YOUR PERL WAS COMPILED. (Sorry for yelling.)
=end original
このドキュメントにあるスクリプトのコンパイルがうまく行かなくても、
あなたは孤独ではありません。
基本的なルールはこうです:
B<あなたが Perl をコンパイルしたときと全く同じやり方でプログラムを
コンパイルしなさい>。
(叫んでしまってすみません。)
=begin original
Also, every C program that uses Perl must link in the I<perl library>.
What's that, you ask? Perl is itself written in C; the perl library
is the collection of compiled C programs that were used to create your
perl executable (I</usr/bin/perl> or equivalent). (Corollary: you
can't use Perl from your C program unless Perl has been compiled on
your machine, or installed properly--that's why you shouldn't blithely
copy Perl executables from machine to machine without also copying the
I<lib> directory.)
=end original
また、Perlを使うすべての C プログラムは I<perl ライブラリ> にリンクして
いなければなりません。
それって何、と聞きますか?
Perl それ自身が C で書かれています。
Perl ライブラリはあなたの perl 実行ファイル(I</usr/bin/perl> か
これに等価な)を作るために使われたコンパイル済みの C プログラムの
集合体です(あなたの使うマシンで Perl がコンパイルされているか、正しく
インストールされていなければ C プログラムから Perl を使うことはできません。
これが、Perl の実行ファイルをあるマシンからマシンへ I<lib> ディレクトリ
抜きでコピーしてしまうような軽率なことをすべきでないという理由です)。
=begin original
When you use Perl from C, your C program will--usually--allocate,
"run", and deallocate a I<PerlInterpreter> object, which is defined by
the perl library.
=end original
Perl を C から使うとき、その C プログラムは -- 普通は -- perl ライブラリで
定義されている I<PerlInterpreter> オブジェクトの割り付け、「実行」、解放を
行います。
=begin original
If your copy of Perl is recent enough to contain this documentation
(version 5.002 or later), then the perl library (and I<EXTERN.h> and
I<perl.h>, which you'll also need) will reside in a directory
that looks like this:
=end original
あなたの使っている Perl がこのドキュメントの内容にあっている(バージョン
5.002 以降)であるのであれば、perl ライブラリ(とこれも必要な
I<EXTERN.H> と I<perl.h>)が次のようなディレクトリに
置かれていることでしょう。
/usr/local/lib/perl5/your_architecture_here/CORE
=begin original
or perhaps just
=end original
あるいは以下のような場所かもしれませんし
/usr/local/lib/perl5/CORE
=begin original
or maybe something like
=end original
こうかもしれません
/usr/opt/perl5/CORE
=begin original
Execute this statement for a hint about where to find CORE:
=end original
CORE の場所を見つけ出すために以下のような文を実行します。
perl -MConfig -e 'print $Config{archlib}'
=begin original
Here's how you'd compile the example in the next section,
L</Adding a Perl interpreter to your C program>, on my Linux box:
=end original
次のセクション L</Adding a Perl interpreter to your C program> に
ある例をコンパイルするこうします(私のLinux boxでの場合)
% gcc -O2 -Dbool=char -DHAS_BOOL -I/usr/local/include
-I/usr/local/lib/perl5/i586-linux/5.003/CORE
-L/usr/local/lib/perl5/i586-linux/5.003/CORE
-o interp interp.c -lperl -lm
=begin original
(That's all one line.) On my DEC Alpha running old 5.003_05, the
incantation is a bit different:
=end original
(これは実際には一行です。)
私の使う DEC Alpha 上で古い 5.003_05 を使う場合では、オマジナイはちょっと
違います:
% cc -O2 -Olimit 2900 -I/usr/local/include
-I/usr/local/lib/perl5/alpha-dec_osf/5.00305/CORE
-L/usr/local/lib/perl5/alpha-dec_osf/5.00305/CORE -L/usr/local/lib
-D__LANGUAGE_C__ -D_NO_PROTO -o interp interp.c -lperl -lm
=begin original
How can you figure out what to add? Assuming your Perl is post-5.001,
execute a C<perl -V> command and pay special attention to the "cc" and
"ccflags" information.
=end original
追加するのものを見つけるにはどうすればよいでしょうか?
あなたの使う Perl が 5.001 より後のものであれば、C<perl -V> を実行して、
"cc" と "ccflags" の情報に特に注意して見ましょう。
=begin original
You'll have to choose the appropriate compiler (I<cc>, I<gcc>, et al.) for
your machine: C<perl -MConfig -e 'print $Config{cc}'> will tell you what
to use.
=end original
あなたは、あなたの使うマシンのために適切なコンパイラ(I<cc>,
I<gcc> など)を選ぶ必要があります。
C<perl -MConfig -e 'print $Config{cc}'> はあなたに使うべき
コンパイラを教えてくれるでしょう。
=begin original
You'll also have to choose the appropriate library directory
(I</usr/local/lib/...>) for your machine. If your compiler complains
that certain functions are undefined, or that it can't locate
I<-lperl>, then you need to change the path following the C<-L>. If it
complains that it can't find I<EXTERN.h> and I<perl.h>, you need to
change the path following the C<-I>.
=end original
同様に、適切なライブラリディレクトリ(I</usr/local/lib/...>) も
選択せねばなりません。
もしあなたの使うコンパイラが幾つかの関数が
未定義であるとか、I<-lperl> が見つからないという報告をしてきたら、
C<-L> の後に続くパスを変更する必要があります。
I<EXTERN.h> や I<perl.h> が見つからないというエラーであれば、
C<-I> の後にあるパスを変更する必要があります。
=begin original
You may have to add extra libraries as well. Which ones?
Perhaps those printed by
=end original
おそらく、さらにライブラリを追加指定する必要があるでしょう。
どれを?
おそらく以下のようにすれば表示されます:
perl -MConfig -e 'print $Config{libs}'
=begin original
Provided your perl binary was properly configured and installed the
B<ExtUtils::Embed> module will determine all of this information for
you:
=end original
あなたの使っている perl のバイナリが適切なコンフィギュレーションが
行われているもので、かつ B<ExtUtils::Embed> モジュールが
インストールされていれば、これによって必要な全ての情報が決定できます。
% cc -o interp interp.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
=begin original
If the B<ExtUtils::Embed> module isn't part of your Perl distribution,
you can retrieve it from
L<http://www.perl.com/perl/CPAN/modules/by-module/ExtUtils/>
(If this documentation came from your Perl distribution, then you're
running 5.004 or better and you already have it.)
=end original
B<ExtUtils::Embed> モジュールは Perl 配布パッケージに含まれていなければ、
L<http://www.perl.com/perl/CPAN/modules/by-module/ExtUtils/> から
入手できます(もしこのドキュメントがあなたの持っている
Perl 配布パッケージにあったものならば、あなたは 5.004 以降のものを
使っているはずで、すでにそのモジュールを持っているはずです。)
=begin original
The B<ExtUtils::Embed> kit on CPAN also contains all source code for
the examples in this document, tests, additional examples and other
information you may find useful.
=end original
CPAN にある B<ExtUtils::Embed> キットにもこのドキュメントにある例の
すべてのソースコードがあり、テストと追加された例、その他の情報が
あります。
=head2 Adding a Perl interpreter to your C program
(あなたの C プログラムに Perl インタプリタを追加する)
=begin original
In a sense, perl (the C program) is a good example of embedding Perl
(the language), so I'll demonstrate embedding with I<miniperlmain.c>,
included in the source distribution. Here's a bastardized, non-portable
version of I<miniperlmain.c> containing the essentials of embedding:
=end original
ある意味で、perl(C プログラムとしての perl)は組み込み Perl(言語としての
Perl)の良い例です; ですから、ソース配布にある I<miniperlmain.c> を
使って組込みのデモンストレーションをします。
以下に示すのは、組込みの本質を持っていて配布ソースにも含まれている
(そして粗悪で移植性に欠ける)I<miniperlmain.c> です。
#include <EXTERN.h> /* from the Perl distribution */
#include <perl.h> /* from the Perl distribution */
static PerlInterpreter *my_perl; /*** The Perl interpreter ***/
int main(int argc, char **argv, char **env)
{
PERL_SYS_INIT3(&argc,&argv,&env);
my_perl = perl_alloc();
perl_construct(my_perl);
PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
perl_parse(my_perl, NULL, argc, argv, (char **)NULL);
perl_run(my_perl);
perl_destruct(my_perl);
perl_free(my_perl);
PERL_SYS_TERM();
exit(EXIT_SUCCESS);
}
=begin original
Notice that we don't use the C<env> pointer. Normally handed to
C<perl_parse> as its final argument, C<env> here is replaced by
C<NULL>, which means that the current environment will be used.
=end original
ここで、C<env> ポインタを使っていないことに注意してください。
通常は C<perl_parse> はその最終引数として C<env> を取りますが、
ここではカレントの環境をそのまま使うことを示す
C<NULL> に置き換えられています。
=begin original
The macros PERL_SYS_INIT3() and PERL_SYS_TERM() provide system-specific
tune up of the C runtime environment necessary to run Perl interpreters;
they should only be called once regardless of how many interpreters you
create or destroy. Call PERL_SYS_INIT3() before you create your first
interpreter, and PERL_SYS_TERM() after you free your last interpreter.
=end original
PERL_SYS_INIT3() と PERL_SYS_TERM() のマクロは、Perl インタプリタを
実行するのに必要な C ランタイム環境の、システム固有の調整を提供します;
これらはインタプリタが何回作成または破壊されたかに関わらず、1 回だけ
呼び出されるべきです。
最初のインタプリタを作る前に PERL_SYS_INIT3() を呼び出し、
最後のインタプリタを解放した後に PERL_SYS_TERM() を呼び出します。
=begin original
Since PERL_SYS_INIT3() may change C<env>, it may be more appropriate to
provide C<env> as an argument to perl_parse().
=end original
PERL_SYS_INIT3() は C<env> を変更するかもしれないので、perl_parse() の
引数として C<env> を提供する方がより適切です。
=begin original
Also notice that no matter what arguments you pass to perl_parse(),
PERL_SYS_INIT3() must be invoked on the C main() argc, argv and env and
only once.
=end original
また、どんな引数を perl_parse() に渡したかに関わらず、PERL_SYS_INIT3() は
C main() argc, argv, env から一度だけ起動されなければなりません。
=begin original
Mind that argv[argc] must be NULL, same as those passed to a main
function in C.
=end original
C の main 関数に渡されるものと同じように、
argv[argc] は NULL でなければならないことを注意してください。
=begin original
Now compile this program (I'll call it I<interp.c>) into an executable:
=end original
ここでこのプログラム(I<interp.c> と呼びましょう)をコンパイルして
実行ファイルを作りましょう。
% cc -o interp interp.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
=begin original
After a successful compilation, you'll be able to use I<interp> just
like perl itself:
=end original
コンパイルに成功すれば、perl そのものと同じように
I<interp> を使うことができるでしょう。
% interp
print "Pretty Good Perl \n";
print "10890 - 9801 is ", 10890 - 9801;
<CTRL-D>
Pretty Good Perl
10890 - 9801 is 1089
=begin original
or
=end original
または
% interp -e 'printf("%x", 3735928559)'
deadbeef
=begin original
You can also read and execute Perl statements from a file while in the
midst of your C program, by placing the filename in I<argv[1]> before
calling I<perl_run>.
=end original
I<perl_run> を呼び出す前に I<argv[1]> にファイル名を置くことで、
C プログラムの中ほどで Perl 文をファイルから読み込んで実行するという
こともできます。
=head2 Calling a Perl subroutine from your C program
(あなたの C プログラムから Perl のサブルーチンを呼ぶ)
=begin original
To call individual Perl subroutines, you can use any of the B<call_*>
functions documented in L<perlcall>.
In this example we'll use C<call_argv>.
=end original
独立した Perl サブルーチンを呼び出すために、L<perlcall> に記載されている
B<call_*> の類の関数を使うことができます。
次の例では C<call_argv> を使います。
=begin original
That's shown below, in a program I'll call I<showtime.c>.
=end original
以下に示すのは、I<showtime.c> という名前のプログラムです。
#include <EXTERN.h>
#include <perl.h>
static PerlInterpreter *my_perl;
int main(int argc, char **argv, char **env)
{
char *args[] = { NULL };
PERL_SYS_INIT3(&argc,&argv,&env);
my_perl = perl_alloc();
perl_construct(my_perl);
perl_parse(my_perl, NULL, argc, argv, NULL);
PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
/*** skipping perl_run() ***/
call_argv("showtime", G_DISCARD | G_NOARGS, args);
perl_destruct(my_perl);
perl_free(my_perl);
PERL_SYS_TERM();
exit(EXIT_SUCCESS);
}
=begin original
where I<showtime> is a Perl subroutine that takes no arguments (that's the
I<G_NOARGS>) and for which I'll ignore the return value (that's the
I<G_DISCARD>). Those flags, and others, are discussed in L<perlcall>.
=end original
I<showtime> は引数をとらない Perl サブルーチン(I<G_NOARGS>)で、その
戻り値を無視します(I<G_DISCARD>)。
これらのフラグ等は L<perlcall> に説明されています。
=begin original
I'll define the I<showtime> subroutine in a file called I<showtime.pl>:
=end original
I<showtime.pl> と呼ばれるファイルで、I<showtime> サブルーチンを
定義しましょう:
print "I shan't be printed.";
sub showtime {
print time;
}
=begin original
Simple enough. Now compile and run:
=end original
単純にして十分です。
さあコンパイルして実行してみましょう:
% cc -o showtime showtime.c \
`perl -MExtUtils::Embed -e ccopts -e ldopts`
% showtime showtime.pl
818284590
=begin original
yielding the number of seconds that elapsed between January 1, 1970
(the beginning of the Unix epoch), and the moment I began writing this
sentence.
=end original
1970 年 1 月 1 日(UNIX 紀元の開始時点)からこのセンテンスを書いた時点までの
経過秒数が得られます。
=begin original
In this particular case we don't have to call I<perl_run>, as we set
the PL_exit_flag PERL_EXIT_DESTRUCT_END which executes END blocks in
perl_destruct.
=end original
この特殊な状況では、私たちは I<perl_run> を呼ぶ必要はありません;
perl_destruct で END ブロックを実行する
PL_exit_flag PERL_EXIT_DESTRUCT_END をセットしているからです。
=begin original
If you want to pass arguments to the Perl subroutine, you can add
strings to the C<NULL>-terminated C<args> list passed to
I<call_argv>. For other data types, or to examine return values,
you'll need to manipulate the Perl stack. That's demonstrated in
L</Fiddling with the Perl stack from your C program>.
=end original
Perl サブルーチンに引数を渡したいという場合、I<call_argv> に
渡される C<NULL> で終端されたリスト C<args> に文字列を追加することが
できます。
他のデータ型を使ったり戻り値をチェックするには Perl スタックを
操作する必要があるでしょう。
これは本ドキュメントの最後の
セクション L</Fiddling with the Perl stack from your C program> で
説明されています。
=head2 Evaluating a Perl statement from your C program
(CプログラムからPerlの文を評価する)
=begin original
Perl provides two API functions to evaluate pieces of Perl code.
These are L<perlapi/eval_sv> and L<perlapi/eval_pv>.
=end original
Perl は Perl コードのかけら(pieces of Perl code)を評価するための二つの
API 関数を提供しています。
L<perlapi/eval_sv> と L<perlapi/eval_pv> です。
=begin original
Arguably, these are the only routines you'll ever need to execute
snippets of Perl code from within your C program. Your code can be as
long as you wish; it can contain multiple statements; it can employ
L<perlfunc/use>, L<perlfunc/require>, and L<perlfunc/do> to
include external Perl files.
=end original
これらの関数は、C プログラムの中で Perl のコードの断片を実行するのに
必要だったルーチンにすぎません。
あなたはコードを好きなだけ長くでき、複数の文を含むことができます;
また、外部の Perl ファイルを取り込むために L<perlfunc/use>,
L<perlfunc/require>, L<perlfunc/do> を使うことができます。
=begin original
I<eval_pv> lets us evaluate individual Perl strings, and then
extract variables for coercion into C types. The following program,
I<string.c>, executes three Perl strings, extracting an C<int> from
the first, a C<float> from the second, and a C<char *> from the third.
=end original
I<eval_pv> は独立した Perl の文字列を評価し、強制的に C の型へと
変数を展開します。
以下に示すプログラムは I<string.c> は、三つの
Perl 文字列を実行し、最初のものを C<int >に、二番目のものを C<float> に、
三番目のものを C<char *>へ 展開します。
#include <EXTERN.h>
#include <perl.h>
static PerlInterpreter *my_perl;
main (int argc, char **argv, char **env)
{
char *embedding[] = { "", "-e", "0", NULL };
PERL_SYS_INIT3(&argc,&argv,&env);
my_perl = perl_alloc();
perl_construct( my_perl );
perl_parse(my_perl, NULL, 3, embedding, NULL);
PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
perl_run(my_perl);
/** Treat $a as an integer **/
eval_pv("$a = 3; $a **= 2", TRUE);
printf("a = %d\n", SvIV(get_sv("a", 0)));
/** Treat $a as a float **/
eval_pv("$a = 3.14; $a **= 2", TRUE);
printf("a = %f\n", SvNV(get_sv("a", 0)));
/** Treat $a as a string **/
eval_pv(
"$a = 'rekcaH lreP rehtonA tsuJ'; $a = reverse($a);", TRUE);
printf("a = %s\n", SvPV_nolen(get_sv("a", 0)));
perl_destruct(my_perl);
perl_free(my_perl);
PERL_SYS_TERM();
}
=begin original
All of those strange functions with I<sv> in their names help convert Perl
scalars to C types. They're described in L<perlguts> and L<perlapi>.
=end original
名前に I<sv> の付いた奇妙な関数は Perl のスカラから C の型への変換を
手助けします。
これらは L<perlguts> と L<perlapi> に記述されています。
=begin original
If you compile and run I<string.c>, you'll see the results of using
I<SvIV()> to create an C<int>, I<SvNV()> to create a C<float>, and
I<SvPV()> to create a string:
=end original
I<string.c> をコンパイルして実行すれば、I<SvIV()> を使って C<int> を、
I<SvNV()> を使って C<float> を、I<SvPV()> を使って文字列を生成した
結果を見ることになるでしょう。
a = 9
a = 9.859600
a = Just Another Perl Hacker
=begin original
In the example above, we've created a global variable to temporarily
store the computed value of our eval'ed expression. It is also
possible and in most cases a better strategy to fetch the return value
from I<eval_pv()> instead. Example:
=end original
先の例では、私たちが式を評価した値を一時的に格納するためのグローバル
変数を生成しました。
これと同様なことが I<eval_pv()> の戻り値を取ることで可能であり、かつ
ほとんどの場合にはこれが良い戦略なのです。
例えば:
...
SV *val = eval_pv("reverse 'rekcaH lreP rehtonA tsuJ'", TRUE);
printf("%s\n", SvPV_nolen(val));
...
=begin original
This way, we avoid namespace pollution by not creating global
variables and we've simplified our code as well.
=end original
このやり方によればグローバル変数を生成せず、またプログラムを単純に
したことによって名前空間の汚染を防ぎます。
=head2 Performing Perl pattern matches and substitutions from your C program
(CプログラムからPerlのパターンマッチングと置換を使ってみる)
=begin original
The I<eval_sv()> function lets us evaluate strings of Perl code, so we can
define some functions that use it to "specialize" in matches and
substitutions: I<match()>, I<substitute()>, and I<matches()>.
=end original
関数 I<eval_pv> は Perl コードの文字列を評価するものなので、
私たちはマッチや置換に「特化」(specilalize)するために使う
I<match()>, I<substitute()>, I<matches()>といった幾つかの関数を
定義できました。
I32 match(SV *string, char *pattern);
=begin original
Given a string and a pattern (e.g., C<m/clasp/> or C</\b\w*\b/>, which
in your C program might appear as "/\\b\\w*\\b/"), match()
returns 1 if the string matches the pattern and 0 otherwise.
=end original
文字列と C<m/clasp/> や C</\b\w*\b/> のようなパターン(これは
C プログラムでは"/\\b\\w*\\b/" のようになっているでしょう)を与えると、
match() は文字列がパターンにマッチしたときには1を、そうでないときは
0 を返します。
int substitute(SV **string, char *pattern);
=begin original
Given a pointer to an C<SV> and an C<=~> operation (e.g.,
C<s/bob/robert/g> or C<tr[A-Z][a-z]>), substitute() modifies the string
within the C<SV> as according to the operation, returning the number of
substitutions made.
=end original
C<SV> へのポインタと C<=~> 操作(C<s/bob/robert/g> もしくは
C<tr[A-Z][a-z]>)を与えると、substitue() はその操作に従って
C<SV> の中の文字列の書き換えを行って、置換の回数を返します。
SSize_t matches(SV *string, char *pattern, AV **matches);
=begin original
Given an C<SV>, a pattern, and a pointer to an empty C<AV>,
matches() evaluates C<$string =~ $pattern> in a list context, and
fills in I<matches> with the array elements, returning the number of matches
found.
=end original
C<SV>、パターン、空の C<AV> へのポインタを渡すと、
matchs() はリストコンテキストで C<$string =~ $pattern> を評価して
I<matches> を配列の要素(メモリを割り当てます)で満たし、マッチした
回数を返します。
=begin original
Here's a sample program, I<match.c>, that uses all three (long lines have
been wrapped here):
=end original
以下に示すのはサンプルプログラム I<match.c> で、三つの関数すべてを
使います(長い行は整形されてます)。
#include <EXTERN.h>
#include <perl.h>
static PerlInterpreter *my_perl;
/** my_eval_sv(code, error_check)
** kinda like eval_sv(),
** but we pop the return value off the stack
**/
SV* my_eval_sv(SV *sv, I32 croak_on_error)
{
dSP;
SV* retval;
PUSHMARK(SP);
eval_sv(sv, G_SCALAR);
SPAGAIN;
retval = POPs;
PUTBACK;
if (croak_on_error && SvTRUE(ERRSV))
croak_sv(ERRSV);
return retval;
}
/** match(string, pattern)
**
** Used for matches in a scalar context.
**
** Returns 1 if the match was successful; 0 otherwise.
**/
I32 match(SV *string, char *pattern)
{
SV *command = newSV(0), *retval;
sv_setpvf(command, "my $string = '%s'; $string =~ %s",
SvPV_nolen(string), pattern);
retval = my_eval_sv(command, TRUE);
SvREFCNT_dec(command);
return SvIV(retval);
}
/** substitute(string, pattern)
**
** Used for =~ operations that
** modify their left-hand side (s/// and tr///)
**
** Returns the number of successful matches, and
** modifies the input string if there were any.
**/
I32 substitute(SV **string, char *pattern)
{
SV *command = newSV(0), *retval;
sv_setpvf(command, "$string = '%s'; ($string =~ %s)",
SvPV_nolen(*string), pattern);
retval = my_eval_sv(command, TRUE);
SvREFCNT_dec(command);
*string = get_sv("string", 0);
return SvIV(retval);
}
/** matches(string, pattern, matches)
**
** Used for matches in a list context.
**
** Returns the number of matches,