我想包装一个 C++ 例程,它返回一个std::map
整数和指向 C++ 类实例的指针。我在使用 SWIG 时遇到困难,希望能提供任何帮助。我试图通过一个简单的例子来将这个问题归结为它的本质。
标题test.h
定义如下:
/* File test.h */
#include <stdlib.h>
#include <stdio.h>
#include <map>
class Test {
private:
static int n;
int id;
public:
Test();
void printId();
};
std::map<int, Test*> get_tests(int num_tests);
实现定义在test.cpp
below:
/* File test.cpp */
#include "test.h"
std::map<int, Test*> get_tests(int num_tests) {
std::map<int, Test*> tests;
for (int i=0; i < num_tests; i++)
tests[i] = new Test();
return tests;
}
int Test::n = 0;
Test::Test() {
id = n;
n++;
}
void Test::printId() {
printf("Test ID = %d", id);
}
我写了一个SWIG接口文件test.i
尝试适应这个例程,以便我可以返回std::map<int, Test*>
作为 Python 中的字典:
%module test
%{
#define SWIG_FILE_WITH_INIT
#include "test.h"
%}
%include <std_map.i>
%typemap(out) std::map<int, Test*> {
$result = PyDict_New();
int size = $1.size();
std::map<int, Test*>::iterator iter;
Test* test;
int count;
for (iter = $1.begin(); iter != $1.end(); ++iter) {
count = iter->first;
test = iter->second;
PyDict_SetItem($result, PyInt_FromLong(count),
SWIG_NewPointerObj(SWIG_as_voidptr(test), SWIGTYPE_p_Test, SWIG_POINTER_NEW | 0));
}
}
%include "test.h"
我包装例程并编译 SWIG 生成的包装器代码,并将其链接为共享库,如下所示:
> swig -python -c++ -o test_wrap.cpp test.i
> gcc -c test.cpp -o test.o -fpic -std=c++0x
> gcc -I/usr/include/python2.7 -c test_wrap.cpp -o test_wrap.o -fpic -std=c++0x
> g++ test_wrap.o test.o -o _test.so -shared -Wl,-soname,_test.so
然后我希望能够在 Python 中执行以下操作:
import test
tests = test.get_tests(3)
print tests
for test in tests.values():
test.printId()
如果我将其作为脚本运行example.py
但是,我得到以下输出:
> python example.py
{0: <Swig Object of type 'Test *' at 0x7f056a7327e0>, 1: <Swig Object of type 'Test *' at
0x7f056a732750>, 2: <Swig Object of type 'Test *' at 0x7f056a7329f0>}
Traceback (most recent call last):
File "example.py", line 8, in <module>
test.printId()
AttributeError: 'SwigPyObject' object has no attribute 'printId'
任何想法为什么我得到SwigPyObject
实例作为输出,而不是 SWIG 代理Test
?任何帮助将不胜感激!