How can I build a Perl hash in C code?
Asked Answered
U

3

5

I wish to embed a C code in Perl. In this C code I want to read a huge file into memory, make some changes and build a hash (a custom one). I wish to make this hash accessible from my Perl code. Is it possible? How can I reach the goal?

Uniformity answered 5/10, 2010 at 8:46 Comment(0)
R
12

For embedding c in perl, you're looking for XS. Extensive documentation on that can be found in perlxs and perlxstut.

As for building perl data structures from C, you will have to use the parts of the perlapi that deal with hashes. Much documentation on XS already explains various bits of that. The important parts you're looking for are newHV and hv_store.

Here's a tiny (and completely untested) example of something similar to what you might want to do:

SV *
some_func ()
    PREINIT:
        HV *hash;
    CODE:
        hash = newHV();
        hv_stores(hash, "foo", 3, newSViv(42));
        hv_stores(hash, "bar", 3, newSViv(23));
        RETVAL = newRV_noinc((SV *)hash);
    OUTPUT:
        RETVAL

That's an XS subroutine called some_func, that'll build a hash and return a reference to it to perl space:

my $href = some_func();
# $href = { foo => 42, bar => 23 };
Royalroyalist answered 5/10, 2010 at 8:53 Comment(0)
B
3
  • See Internals and C language interface
  • Also have a look at Inline-C for embedded a C code in perl:The Inline module allows you to put source code from other programming languages directly "inline" in a Perl script or module. The code is automatically compiled as needed, and then loaded for immediate access from Perl.

Also read Why should I use Inline to do it?

Beverly answered 5/10, 2010 at 8:49 Comment(2)
Oh please stop recommending Inline as the de-facto standard solution to such things. It's a deployment nightmare. Unless the requirement is specifically "I need to do this on my machine and my machine only", Inline translates to problems down the road.Beaton
I'll write XS code when I have to, but when I don't have to, Inline::C is awesome.Readjustment
J
1

You can use SWIG to interface between C, Perl, and several other languages.

Judaism answered 5/10, 2010 at 8:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.