沿着这个问题的思路,假设我们有一个 C++
struct S
和一个函数 makeS
,它创建 S
的实例并将其分配给共享指针 p
。这是一个独立的运行示例:
#include <iostream>
#include <memory>
struct S
{
int x;
S() { x = 0; std::cout << "S::S()\n"; }
// Note: non-virtual destructor is OK here
~S() { std::cout << "S::~S()\n"; }
};
void makeS(std::shared_ptr<S> &p)
{
p = std::make_shared<S>();
p->x = 12;
}
int main()
{
std::shared_ptr<S> p;
makeS(p);
std::cout << "x = " << p->x << "\n";
}
输出
S::S()
x = 12
S::~S()
我们如何将
void makeS(std::shared_ptr<S> &p)
包装在 Python 3 的 SWIG 中,以便在 Python 中运行
p = makeS()
并获取指向
S
实例的智能指针?换句话说,我们如何为%typemap
编写基于Python的std::shared_ptr<S> &
,以便我们可以编写类似的内容
%apply std::shared_ptr<S> &OUTPUT { std::shared_ptr<S> & }
并且没有从 SWIG 收到没有定义类型映射的错误?
我目前没有可用的计算机来测试工作示例,但您需要在 SWIG .i 文件中添加以下内容,然后再
%include
定义使用共享指针的函数的标头以及 %apply
之前:
%include <typemaps.i> // for OUTPUT
%include <std_shared_ptr.i>
%shared_ptr(S);
然后使用您的 %apply 和 %include 标头。