1

I am trying too use my C++ class in PHP. in my C++ code I have declared the typedef as:

typedef unsigned char byte;

so I intended to let SWIG consider my typedef in wrapper class, my interface file is something like this:

%module xxx

typedef unsigned char byte;

%include "xxx.h"

....

%{

typedef unsigned char byte;

#include "xxx.h"

%}

and in my test code I refer to type as:

byte *data;

but I've got the following error:

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

P.S: I also include "stdint.i" in my interface file but got the same error

Any ideas?

Flexo
  • 87,323
  • 22
  • 191
  • 272
A23149577
  • 2,045
  • 2
  • 40
  • 74

1 Answers1

0

I can confirm that the interface you've shown is viable and works for simple cases, e.g. I wrote the following header file to test:

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

And used the interface:

%module xxx

typedef unsigned char byte;

%include "xxx.h"

%{
typedef unsigned char byte;

#include "xxx.h"
%}

Which I was able to compile and test with the following PHP:

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

and it worked as expected.

A few points to note from that though:

  1. In general I would be inclined to write the code you want passed through to the module (i.e. the bits inside the %{ %} before your %include.
  2. Rather than using your own typedef for byte I'd be inclined to use one of the standard int types, e.g. uint8_t
  3. It's not clear from your question quite how you intend to use byte *data - presumably it's an array in which case you'll want to add a little more code to your interface. (Or better still use std::vector<byte> since it's C++):

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

    Which can then be used in PHP as:

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

    ByteArray is a utility class provided by SWIG to hold and wrap a raw C array of bytes.

Flexo
  • 87,323
  • 22
  • 191
  • 272
  • thank you so much for your help, it works fine now, I had a mistake in PHP code and my byte type is recognized by PHP. – A23149577 Sep 08 '12 at 06:43