2012-09-04 41 views
1

我想在PHP中使用我的C++類。在我的C++代碼,我宣佈的typedef爲:SWIG typedef recognition

typedef unsigned char byte; 

,所以我打算讓痛飲考慮我的包裝類的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」,但得到了相同的錯誤

任何想法?

+0

非常感謝您Flexo;) – A23149577

回答

0

我可以確認您顯示的界面是可行的,適用於簡單的情況,例如,我寫了下面的頭文件進行測試:

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. 。而不是用自己的typedef byte我傾向於使用標準INT類型中的一種,例如uint8_t
  3. 這不是從你的問題清楚你很打算如何使用byte *data - 想必這是一個在這種情況下,您需要將add a little more code添加到您的界面。 (或者,更好的是使用std::vector<byte>因爲它是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提供的工具類來保存和包裝一個純粹的C陣列byte s。

+0

非常感謝您的幫助,現在工作正常,我在PHP代碼中遇到了錯誤,並且我的字節類型被PHP識別。 – A23149577