Swig:如何从SwigpyObject获取包装std :: shared_ptr的值

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

本文关键字:shared std ptr 的值 包装 获取 SwigpyObject Swig      更新时间:2023-10-16

我正在尝试为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以indeck getActivationCode((方法?

您可以在对象上调用该方法,但是请注意,您需要在包括标头(标头(之前声明%shared_ptr。这是一个工作的独立示例。我刚刚将标头插入了一个单文件解决方案:

%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对象:

>>> 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'