SWIG:如何从SwigPyobject

时间:2019-05-14 13:07:54

标签: python c++ swig

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

1 个答案:

答案 0 :(得分:0)

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