Santosh
Santosh

Reputation: 147

typedef does not work with SWIG (python wrapping C++ code)

Hello and thanks for your help in advance !

I am writing a python wrapper (SWIG 2.0 + Python 2.7) for a C++ code. The C++ code has typedef which I need to access in python wrapper. Unfortunately, I am getting following error when executing my Python code:

 tag = CNInt32(0)
   NameError: global name 'CNInt32' is not defined

I looked into SWIG documentation section 5.3.5 which explains size_t as typedef but I could not get that working too.

Following is simpler code to reproduce the error:

C++ header:

#ifndef __EXAMPLE_H__  
#define __EXAMPLE_H__  

/* File: example.h */
#include <stdio.h>

#if defined(API_EXPORT)
    #define APIEXPORT __declspec(dllexport)
#else
   #define APIEXPORT __declspec(dllimport)
#endif

typedef int CNInt32;

class APIEXPORT ExampleClass {
public:
  ExampleClass();
  ~ExampleClass();  

  void printFunction (int value);
  void updateInt (CNInt32& var);
};

#endif //__EXAMPLE_H__

C++ Source:

/* File : example.cpp */
#include "example.h"
#include <iostream>
using namespace std;

/* I'm a file containing use of typedef variables */
ExampleClass::ExampleClass() {
}

ExampleClass::~ExampleClass() {
}

void ExampleClass::printFunction  (int value) {
cout << "Value = "<< value << endl;
}

void ExampleClass::updateInt(CNInt32& var) {
  var = 10;
}

Interface file:

/* File : example.i */
%module example

typedef int CNInt32;  

%{
    #include "example.h"
%}

%include <windows.i>
%include "example.h"  

Python Code:

# file: runme.py  
from example import *

# Try to set the values of some typedef variables

exampleObj = ExampleClass()
exampleObj.printFunction (20)

var = CNInt32(5)
exampleObj.updateInt (var)

Thanks again for your help.

Santosh

Upvotes: 4

Views: 1720

Answers (1)

Santosh
Santosh

Reputation: 147

I got it working. I had to use typemaps in the interface file, see below:
- Thanks a lot to "David Froger" on Swig mailing lists.
- Also, thanks to doctorlove for initial hints.

%include typemaps.i
%apply CNInt32& INOUT { CNInt32& };

And then in python file:

var = 5                             # Note: old code problematic line: var = CNInt32(5)
print "Python value = ",var
var = exampleObj.updateInt (var)    # Note: 1. updated values returned automatically by wrapper function.
                                    #       2. Multiple pass by reference also work.
                                    #       3. It also works if your c++ function is returning some value.
print "Python Updated value var = ",var

Thanks again !
Santosh

Upvotes: 3

Related Questions