【问题标题】:How do I use a pointer to char from SWIG, in Perl?如何在 Perl 中使用指向 SWIG 中的 char 的指针?
【发布时间】:2009-09-07 05:01:27
【问题描述】:

我使用SWIG 为 C++ 程序生成 Perl 模块。我在 C++ 代码中有一个函数,它返回一个“char 指针”。现在我不知道如何在 Perl 中打印或获取返回的 char 指针。

示例 C 代码:

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

我想在 Perl 中调用这个函数“result”并打印字符串。

如何做到这一点?

问候, 阿南丹

【问题讨论】:

  • 能否提供示例代码?
  • 提供你的接口文件和你的cpp文件的完整代码。

标签: c++ perl swig


【解决方案1】:

根据 C++ 接口的复杂性,跳过 SWIG 并自己编写 XS 代码可能更容易、更快且更易于维护。 XS&C++ 有点神秘。这就是为什么在 CPAN 上有 Mattia Barbon 出色的 ExtUtils::XSpp 模块。它使包装 C++ 变得容易(而且几乎很有趣)。

ExtUtils::XSpp 发行版包括一个非常简单(并且做作的)example 类,它有一个字符串 (char*) 和一个整数成员。以下是精简后的接口文件的样子:

// 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 );
};

请注意,这仍然需要有效的 XS 类型映射。这真的很简单,所以我不会在这里添加它,但你可以在上面链接的示例分发中找到它。

【讨论】:

    【解决方案2】:

    您必须参考 www.swig.org/tutorial.html 上的 SWIG 教程
    无论如何,因为您只想从 perl 调用 C 函数,
    1. 键入您的接口文件(在包装器和模块部分中包含所有函数声明)。
    2. 使用 swig 和 options 编译。
    3. 用 gcc 编译创建对象。
    4. 使用 gcc 选项编译以创建共享对象。
    5.运行程序如下:

    perl  
    use moduleName;  
    $a = moduleName::result();  
    

    [注意:查看生成的模块文件(.pm)以获取正确的函数原型,该原型指向包装文件中的正确函数。]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-26
      • 2018-04-05
      • 1970-01-01
      • 2011-04-24
      • 2016-01-26
      • 2018-06-08
      • 1970-01-01
      • 2016-01-27
      相关资源
      最近更新 更多