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 C ++ code. C ++ code has a typedef that I need to get in the python shell. Unfortunately, I get the following error while executing my Python code:

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

I looked through section 5.3.5 of the SWIG documentation explaining the size_t size as a typedef, but I also could not get this to work.

Below is a 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.

Santos

+4
source share
1 answer

. typemaps , . :
- Swig.
- , Doctorlove .

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

Python:

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

!

+3

Source: https://habr.com/ru/post/1545204/


All Articles