tags:

views:

260

answers:

1

Hi,

I used SWIG to generate a Perl module for a C++ program. I have one function in the C++ code which returns a "char pointer". Now I dont know how to print or get the returned char pointer in Perl.

Sample C code:

 char* result() { 
     return "i want to get this in perl"; 
 }

I want to invoke this function "result" in Perl and print the string.

How to do that?

Regards, Anandan

+5  A: 

Depending on the complexity of the C++ interface, it may be easier, faster, and more maintainable to skip SWIG and write the XS code yourself. XS&C++ is a bit of an arcane art. That's why there is Mattia Barbon's excellent ExtUtils::XSpp module on CPAN. It make wrapping C++ easy (and almost fun).

The ExtUtils::XSpp distribution includes a very simple (and contrived) example of a class that has a string (char*) and an integer member. Here's what the cut-down interface file could look like:

// This will be used to generate the XS MODULE line
%module{Object::WithIntAndString};

// Associate a perl class with a C++ class
%name{Object::WithIntAndString} class IntAndString
{
  // can be called in Perl as Object::WithIntAndString->new( ... );
  IntAndString();

  // Object::WithIntAndString->newIntAndString( ... );
  // %name can be used to assign methods a different name in Perl
  %name{newIntAndString} IntAndString( const char* str, int arg );

  // standard DESTROY method
  ~IntAndString();

  // Will be available from Perl given that the types appear in the typemap
  int GetInt();
  const char* GetString ();

  // SetValue is polymorphic. We want separate methods in Perl
  %name{SetString} void SetValue( const char* arg = NULL );
  %name{SetInt} void SetValue( int arg );
};

Note that this still requires a valid XS typemap. It's really simple, so I won't add it here, but you can find it in the example distribution linked above.

tsee
hi..thanks. but i want to do this in swig..
Anandan