[英]How to handle Method returning nullptr for shared_ptr in SWIG (C++ to Java)
I need to port an existing C++ library to Java. 我需要将现有的C ++库移植到Java。 In the C++ code there is a factory method:
在C ++代码中,有一个工厂方法:
std::shared_ptr<Role> createRole(std::string name)
which will return a nullptr
if it was not possible to create the Role. 如果无法创建角色,它将返回
nullptr
。
Unfortunately if I try to port this code with SWIG it will fail silently at this point. 不幸的是,如果我尝试使用SWIG移植此代码,则此刻它会静默失败。 I guess that is because Java doesn't know about
nullptr
and SWIG is most likely ignoring it. 我猜这是因为Java不了解
nullptr
而SWIG最有可能忽略它。 Is my assumption right? 我的假设正确吗? Because I'm originally a Java developer and don't know much about SWIG and C++...
因为我最初是Java开发人员,对SWIG和C ++不太了解。
Sadly I can't change the existing C++ code. 可悲的是,我无法更改现有的C ++代码。 Is there any workaround for this?
有什么解决方法吗? Or will I have to write a Wrapper for this special case?
还是我需要为这种特殊情况编写包装纸? This problem occures in 4 or 5 places in the project.
在项目中的4或5个位置中会出现此问题。
The problem is highly likely in your code. 您的代码中很有可能出现此问题。 I just checked out the following code with gcc-4.8 and swig-2.0, and it worked perfectly:
我刚刚用gcc-4.8和swig-2.0签出了以下代码,它运行良好:
test.h 测试
#include <string>
#include <memory>
class Test {
public:
std::shared_ptr<std::string> test(bool isNull) {
return isNull ? nullptr : std::make_shared<std::string>("test");
}
};
test.i 测试
%module "test"
%include "std_shared_ptr.i"
%include "std_string.i"
%shared_ptr( std::string )
%{
#include "test.h"
%}
%include "test.h"
check.py check.py
import test
t = test.Test()
print t.test(True)
print t.test(False)
The output of python check.py
is: python check.py
的输出是:
None
没有
<Swig Object of type 'std::shared_ptr< std::string > *' at 0x7f03436501e0>swig/python detected a memory leak of type 'std::shared_ptr< std::string > *', no destructor found.<0x7f03436501e0上类型为'std :: shared_ptr <std :: string> *'的Swig对象> swig / python检测到类型为'std :: shared_ptr <std :: string> *'的内存泄漏,未发现析构函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.