typedef在SWIG中不起作用(Python封装C++代码)
你好,感谢你提前的帮助!
我正在为一段C++代码写一个Python的封装器(使用SWIG 2.0和Python 2.7)。这段C++代码里有一些类型定义(typedef),我需要在Python封装器中访问这些类型。可是,当我运行我的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)
再次感谢你的帮助。
Santosh
1 个回答
3
我搞定了这个问题。为了让它正常工作,我在接口文件中使用了类型映射,具体内容见下面:
- 非常感谢“David Froger”在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
再次感谢!
Santosh