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以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'
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- std::具有相同基类的类的变体
- std::向量与传递值的动态数组
- 使用std::vector的OpenCL矩阵乘法
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- std::condition_variable::wait()如何评估给定的谓词
- 如何获取std::result_of函数的返回类型
- std::原子加载和存储都需要吗
- 将对象移动到std::shared_ptr
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 引用 std::shared:ptr 以避免引用计数
- boost::shared_ptr和std::shared-ptr的同居
- 我可以用std::shared_ptr而不是boost::shared-ptr构建boost库吗
- std::dynamic_pointer_cast从基到派生的std::shared返回NULL
- QSharedPointer VS std::tr1::shared_ptr VS boost::tr1::shared