Brett W. McCoy <[EMAIL PROTECTED]> writes: >I am building an embedded Perl scripting environment for a 3D modelling >package. I have the basic scripting engine working (that was the easy >part), but now my challenge is to be able to directly interface with C++ >objects inside the application. What I really want to do is to be able >to build Perl objects on the fly from live C++ objects.
Which can be done if you have a clear policy for how a C++ object becomes a perl object. The snag is that C++ is compile time typed so each C++ class needs a "method" to convert itself to/from perl objects. I have some day-job related code (which I have yet to shake loose into something I can distribute) which uses g++ -E and then a "parse" of result to create perl bindings to all the public methods of a class heirachy. (i.e. you use it instead of xsubpp and it produces Class.cpp). At bottom of this are the utility functions: void * SV_to_object(pTHX_ SV *sv, const char *classname) { if (SvOK(sv)) { if (sv_derived_from(sv,classname) && SvIOK(SvRV(sv))) { IV tmp = SvIV(SvRV(sv)); return (void *) INT2PTR(void *,tmp); } croak("Not a %s (%_)",classname,sv); } return 0; } void object_to_SV(pTHX_ SV **svp, const char *classname, IV value) { if (value) { SV *sv = sv_newmortal(); sv_setref_iv(sv,classname,value); *svp = sv; } else { *svp = &PL_sv_undef; } } void enum_to_SV(pTHX_ SV **svp, const char *classname, IV value, const char *str = 0) { SV *sv = sv_newmortal(); *svp = sv; sv_setref_iv(sv,classname,value); if (str) { sv_upgrade((sv = SvRV(sv)),SVt_PVIV); sv_setpv(sv,str); SvIOK_on(sv); } } IV SV_to_enum(pTHX_ SV *sv, const char *classname) { if (sv_derived_from(sv,classname) && SvIOK(SvRV(sv))) { return SvIV(SvRV(sv)); } croak("Not a %s (%_)",classname,sv); return 0; } The perl script (which I call findclass) then arranges to pass right thing to classname args of those. The perl classnames are same as the C++ ones. The fun part is handling overloaded functions - i.e. figuring out from the number and type of args passed which C++ method to call and producing "XS code" that calls method with correctly converted args to call that method. >For instance, >the user has the application running with an open document with a >hierarchy of objects, and each level (application, document, object) >has a certain scripting context associated with it (not too different >from DOM, I think), so you can run, say, a script that modifies the >behavior of a group of objects as they are being animated. > >I found, on CPAN, an aborted attempt at creating a C++ interface to the >Perl API, and that might be a good starting point, but I wanted to see >if anyone else has ventured into this arena. You can embed perl in C++ using perl's C API. You just have to to C-ish housekeeping rather than C++-ish housekeeping. -- Nick Ing-Simmons http://www.ni-s.u-net.com/