【问题标题】:SWIG typedef recognitionSWIG typedef 识别
【发布时间】:2012-09-04 05:45:55
【问题描述】:

我也在尝试在 PHP 中使用我的 C++ 类。在我的 C++ 代码中,我将 typedef 声明为:

typedef unsigned char byte;

所以我打算让 SWIG 在包装类中考虑我的 typedef,我的接口文件是这样的:

%module xxx

typedef unsigned char byte;

%include "xxx.h"

....

%{

typedef unsigned char byte;

#include "xxx.h"

%}

在我的测试代码中,我将类型称为:

byte *data;

但我收到以下错误:

Fatal error: Class 'unsigned_char' not found in xxx.php

P.S:我还在接口文件中包含“stdint.i”,但得到了同样的错误

有什么想法吗?

【问题讨论】:

    标签: swig typedef


    【解决方案1】:

    我可以确认您显示的界面是可行的,并且适用于简单的情况,例如我写了如下头文件来测试:

    byte *make() { return NULL; }
    void consume(byte *data) {}
    

    并使用了接口:

    %module xxx
    
    typedef unsigned char byte;
    
    %include "xxx.h"
    
    %{
    typedef unsigned char byte;
    
    #include "xxx.h"
    %}
    

    我能够使用以下 PHP 进行编译和测试:

    <?php
    include("xxx.php");
    $r = xxx::make();
    xxx::consume($r);
    ?>
    

    它按预期工作。

    不过有几点需要注意:

    1. 一般来说,我倾向于编写您想要传递给模块的代码(即%{ %} 中的位在您的%include 之前。
    2. 我倾向于使用标准的 int 类型之一,而不是使用您自己的 typedef byte,例如uint8_t
    3. 从您的问题中不清楚您打算如何使用byte *data - 大概它是一个数组,在这种情况下您需要add a little more code 到您的界面。 (或者最好还是使用std::vector&lt;byte&gt;,因为它是 C++):

      %module xxx
      
      %{
      typedef unsigned char byte;
      
      #include "xxx.h"
      %}
      
      %include <carrays.i>
      
      %array_class(byte,ByteArray);
      
      typedef unsigned char byte;
      
      %include "xxx.h"
      

      然后可以在 PHP 中用作:

      $a = new ByteArray(100);
      $a->setitem(0, 1);
      $a->setitem(1, 2); //...
      xxx::consume($a->cast());
      

      ByteArray 是 SWIG 提供的实用程序类,用于保存和包装 bytes 的原始 C 数组。

    【讨论】:

    • 非常感谢您的帮助,现在可以正常使用了,我的 PHP 代码出错了,我的字节类型被 PHP 识别了。
    猜你喜欢
    • 1970-01-01
    • 2016-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-15
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    相关资源
    最近更新 更多