【问题标题】:SWIG: How to get value of wrapped std::shared_ptr from SwigPyobjectSWIG:如何从 SwigPyobject 获取包装的 std::shared_ptr 的值
【发布时间】:2019-05-14 13:07:54
【问题描述】:

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

【问题讨论】:

    标签: python c++ swig


    【解决方案1】:

    您可以只调用对象上的方法,但请注意您需要在 %include 标头之前声明 %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'
    

    【讨论】:

    • 谢谢。它有帮助。所以主要问题是我把 %shared_ptr 放在了错误的地方
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-18
    • 2015-12-15
    • 2020-09-19
    • 1970-01-01
    • 2016-12-05
    相关资源
    最近更新 更多