Using Perl with compiled C library?
I would like to try and use Perl, but need to communicate with another application I wrote. I have an interface library that I wrote in C++, and it contains the socket communications and interface protocol to set/get parameters in my application.
I would like to use P开发者_如何学Pythonerl with Apache to serve up web pages for configuring my application. I need to know how to get Perl to talk to my interface library.
Oh Lord, if you are new to Perl. you do not want to be looking at XS (I am not new to Perl and I do not want to look at XS). See Inline::C or Inline::CPP for a much gentler introduction to calling C and C++ from Perl. Drilling deeper into the XS interface should only be necessary if you want to start passing or returning complicated data structures around (and maybe not even then).
use Inline C => Config => LIBS => '-L/<yourlibpath> -l<yourlib>';
$x = my_library_function_that_returns_an_int_or_double($integer_arg,$string_arg);
It looks like you want to communicate with a C library from Perl. You'll want to read through perldoc perlxs and perldoc perlxstut for more about the XS interface. If you want to do the reverse (call Perl from C), also read through perldoc perlguts and perldoc perlembed.
When you encounter specific problems, give SO another holler and someone can surely help you out. :)
If you chose not to go the inline-C route, Perl has built in support for sockets, A great tutorial on doing IPC, and a few objects to help with sockets in general (plus, google will provide you many other tutorials on using perl sockets). If you're able/willing to re-implement the sockets communication part, you may not even need the C/C++.
You need to create a module for you C++ library, if you don't want to use Inline::CPP. It can be done automatically with h2xs: h2xs --autogen-xsubs
. Install C::Scan from CPAN first.
First, let me say that XS a relatively small set of keywords that makes wrapping C libraries for use from perl easier (see perlxstut and perlxs). In order to use it, however, you will have to learn the perl API (see perlapi) which in turn requires a shallow knowledge of how the perl compiler works (see perlguts and the somewhat outdated but still highly useful perl guts illustrated). That's a lot to learn at the same time. In short:
- XS itself => not hard
- perlapi => moderately hard
- perl inner workings => pretty hard
- all of the above at the same time => ouch
That being said, if you want to wrap a C++ library, have a look at the ExtUtils::XSpp module on CPAN. It comes with a very simple example. The module's not that old and still being improved, but it makes wrapping C++ a lot more convenient.
PS: If you plan to learn everything at once, learn by examples. Check out Dean Roehrich's cookbooks. Maybe use some simple XS modules as models: Parse::ExuberantCTags, Math::FFTW or one of the many others on CPAN.
精彩评论