SWIG:如何从 SwigPyobject 中获取包装 std::shared_ptr 的值

SWIG: How to get value of wrapped std::shared_ptr from SwigPyobject

我正在尝试为 C++ 库创建一个 SWIG Python 接口,为某些函数添加 Python 包装器,非常感谢有 SWIG 经验的人提供的帮助。

目前我有这样的来源:

test.h

namespace Test {
class CodeResponseEvent {
 public:
  CodeResponseEvent(std::string activation_code);
  std::string getActivationCode() const;
 private:
  const std::string activation_code_;
};

class CodeRequestEvent {
 public:
  CodeRequestEvent(std::string user_id);
  std::shared_ptr<CodeResponseEvent> execute();

 private:
  const std::string user_id_;
};
}

test.i

%module test
%include std_string.i
%include <std_shared_ptr.i>

%{#include "test.h"%}
%include "test.h"
%shared_ptr(Test::CodeResponseEvent);

Python 代码如下:

codeResponse = test.CodeRequestEvent("user").execute()

结果我得到了价值

<Swig Object of type 'std::shared_ptr< Test::CodeResponseEvent> *'>

所以问题是如何打开这个 SwigPyobject 以调用 getActivationCode() 方法?

您可以只调用 object 上的方法,但请注意您需要在 %including header 之前声明 %shared_ptr。这是一个独立的工作示例。我刚刚将 header 内联为 one-file 解决方案:

%module test
%include std_string.i
%include <std_shared_ptr.i>

%shared_ptr(Test::CodeResponseEvent);

%inline %{
#include <memory>
#include <string>
namespace Test {
class CodeResponseEvent {
 public:
  CodeResponseEvent(std::string activation_code) : activation_code_(activation_code) {}
  std::string getActivationCode() const { return activation_code_; }
 private:
  const std::string activation_code_;
};

class CodeRequestEvent {
 public:
  CodeRequestEvent(std::string user_id):user_id_(user_id) {};
  std::shared_ptr<CodeResponseEvent> execute() { return std::make_shared<CodeResponseEvent>("Hi"); }

 private:
  const std::string user_id_;
};
}
%}

演示如下。请注意 r 是代理而不是通用 Swig Object 如果共享指针在使用前声明:

>>> import test
>>> r = test.CodeRequestEvent('user').execute()
>>> r
<test.CodeResponseEvent; proxy of <Swig Object of type 'std::shared_ptr< Test::CodeResponseEvent > *' at 0x0000027AF1F97330> >
>>> r.getActivationCode()
'Hi'