typedef不适用于SWIG(python包装C代码)

您好,感谢您的帮助!

我正在为C代码编写一个python包装器(SWIG 2.0 Python 2.7). C代码有我需要在python包装器中访问的typedef.不幸的是,我在执行Python代码时遇到以下错误:

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

我查看了SWIG文档部分5.3.5,它将size_t解释为typedef,但我也无法解决这个问题.

以下是重现错误的简单代码:

C头:

#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来源:

/* 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;
}

接口文件:

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

typedef int CNInt32;  

%{
    #include "example.h"
%}

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

Python代码:

# 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)

再次感谢你的帮助.

桑托斯

最佳答案 我搞定了.我不得不在接口文件中使用类型映射,见下文:

   – 非常感谢Swig邮件列表中的“David Froger”.

   – 另外,感谢doctorlove的初步提示.

%include typemaps.i
%apply int& 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

再次感谢 !
桑托斯

点赞