SWIG:如何从SwigPyobj获取包装的std::shared\u ptr的值

2024-03-29 15:59:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试为C++库创建一个Spy-Python接口,为一些函数添加Python包装,我将非常感激来自Sigg的一些人的帮助。你知道吗

目前我有这样的消息来源:

试验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_;
};
}

测试.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()方法?你知道吗


Tags: teststringincludecodepublicactivationclassshared
1条回答
网友
1楼 · 发布于 2024-03-29 15:59:08

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

相关问题 更多 >