【发布时间】:2018-05-22 16:21:58
【问题描述】:
我在 C++ 中有以下内容:
#ifndef INTERFACE_H
#define INTERFACE_H
class Interface {
public:
virtual void blah() = 0;
};
#endif
#ifndef USER_H
#define USER_H
#include "Interface.h"
#include <iostream>
class User {
public:
void callBlah(Interface* ptr) {
ptr->blah();
}
};
#endif
我有这个 SWIG 接口文件:
%module(directors="1") interface
%{
#include "Interface.h"
#include "User.h"
%}
%feature("director") Interface;
%include "Interface.h"
%include "User.h"
我编译了:
$ swig -Wall -c++ -python -I/usr/include/python3.6m interface.i
Interface.h:3: Warning 514: Director base class Interface has no virtual destructor.
$ g++ -shared -fPIC -I/usr/include/python3.6m Foo.cpp interface_wrap.cxx -o _interface.so
然后,我跑了:
import interface
class Implementation(interface.Interface):
def __init__(self):
super().__init__()
self.__something = 1
def blah(self):
print("called python version")
i = Implementation().__disown__
u = interface.User()
u.callBlah(i)
它给了:
Traceback (most recent call last):
File "test.py", line 12, in <module>
u.callBlah(i)
File "/home/foo/test/swig/interface.py", line 142, in callBlah
return _interface.User_callBlah(self, ptr)
TypeError: in method 'User_callBlah', argument 2 of type 'Interface *'
所以主要问题是变量 i 是 Implementation 的对象(它实现了接口)但 User::callBlah() 期望参数是指向接口的指针。
我的问题是如何在不更改 C++ 代码的情况下将 i 转换为指向实现/接口的指针?
谢谢!
【问题讨论】:
-
这应该“正常工作”,我看不出它为什么不工作。
-
原来用 i = Implementation() 替换 i = Implementation().__disown__ 可以解决问题。
标签: python c++ python-3.x swig