如何使用swig包装器在c++类指针上调用方法
How do I invoke a method on a C++ class pointer with swig wrappers?
我使用SWIG包装c++代码,以便在Python测试框架中使用。我的问题是,我得到一个指针的一个类的实例,我需要然后调用方法。例如,在我的swig文件example.i:
iExample* getMyClassInstance();
...
class iExample
{
public:
virtual void somePureVirtualMethod() = 0;
// ...
};
在python中,如果我有这个类,我可以调用方法
myClassInstance.somePureVirtualMethod()
当然,我实际上并没有类的实例。我有一个从SWIG生成的不透明指针。我如何使用它?显然,在Python中我不能做
myClassInstancePtr = example.getMyClassInstance()
myClassInstancePtr->somePureVirtualMethod()
我尝试使用cpointer。I或指针。我在swig中生成指针函数,但这不好,因为它试图创建类的副本。这甚至不能与带有纯虚方法的接口进行编译,即使我没有使用纯虚方法,我也不想创建类的副本,我只想在它上面调用一些东西!
SWIG可以很好地处理这个问题。确保在SWIG中定义接口,这样它就不会是不透明的。下面是一个工作示例:
%module x
%inline %{
// Define the interface.
struct iExample
{
virtual int somePureVirtualMethod() = 0;
};
iExample* getMyClassInstance();
%}
// Implementation, not exposed to Python
%{
struct Internal : public iExample
{
int somePureVirtualMethod() { return 5; }
};
iExample* getMyClassInstance() { return new Internal(); }
%}
演示:>>> import x
>>> i = x.getMyClassInstance()
>>> i.somePureVirtualMethod()
5
然而,这个实现会泄漏一个内部实例。您可能希望实现一种自动释放它的方法。一种方法是使用%newobject
并定义虚析构函数。当不再有对该对象的引用时,Python将删除该对象。
%module x
%newobject getMyClassInstance;
%inline %{
struct iExample
{
virtual ~iExample() {};
virtual int somePureVirtualMethod() = 0;
};
iExample* getMyClassInstance();
%}
// Implementation
%{
#include <iostream>
struct Internal : public iExample
{
int somePureVirtualMethod() { return 5; }
~Internal() { std::cout << "destroyed" << std::endl; }
};
iExample* getMyClassInstance() { return new Internal(); }
%}
演示:>>> import x
>>> i = x.getMyClassInstance()
>>> i.somePureVirtualMethod()
5
>>> i=2 # reassign i
destroyed # garbage-collected
我发现最简单的答案是编辑您的示例。我需要添加一些辅助函数来解引用。在你的swig文件example.i:
{%
...
// Helper function to dereference pointers within python
template <typename T>
T& dereference(T* ptr)
{
return *ptr;
}
...
%}
...
// Make every version of the templated functions we'll need
template <typename T> T& dereference(T* ptr);
%template(dereferencePtr_iExample) dereference<iExample>;
现在在python中
myClassInstance = example.dereferencePtr_iExample(example.getMyClassInstance())
myClassInstance.somePureVirtualMethod()
我想这个方法应该也适用于其他语言,比如perl,你不需要和SWIG的typemaps打交道。
相关文章:
- 为什么使用 "this" 指针调用派生成员函数?
- 当使用通配符和null指针调用函数时,对输出的说明
- Visual c ++,使用字符串引用/指针调用 dll 函数
- 使用基类指针调用基类的值构造函数的语法是什么?
- 是否可以使用函数指针调用虚拟析构函数?
- 使用C++指针调用 python 函数
- 如何使用接口指针调用方法,该指针是其具体类的一部分,而不是接口的一部分
- 是否可以使用非常量指针调用非常量函数,以及当两个unique_ptrs指向同一个对象时程序的行为方式?
- 在将派生类指针类型转换为派生类指针后,从基类指针调用派生类函数
- 通过指针调用模板类成员函数 [为什么这是有效的 c++]?
- 从带有参数的基函数指针调用基方法
- 使用唯一指针调用函数会使我的程序崩溃
- C++::在构造函数退出之前通过指针调用成员函数
- 有没有办法在没有虚拟的情况下使用基类指针调用派生类函数
- 什么时候用指针调用C++类构造函数
- C++ - 使用变量指针调用函数
- 为什么我可以通过野生指针调用成员函数
- 从指针调用方法时出现分段错误
- 为什么使用指向函数的指针调用虚函数时不需要指针"this"?
- C++ abort() 在函数内的抽象类对象指针调用上