我试图忽略 std::enable_shared_from_this 基类。
以下是我的档案
测试.h:
#ifndef _TEST_H_INCLUDED_
#define _TEST_H_INCLUDED_
#include <memory>
class Test : public std::enable_shared_from_this<Test> {
public:
Test() : val_(0) {}
virtual ~Test() {}
int GetVal() const;
void SetVal(int val);
private:
int val_;
};
#endif // _TEST_H_INCLUDED_
test.cpp:
#include "test.h"
int Test::GetVal() const { return val_; }
void Test::SetVal(int val) { val_ = val; }
test_module.i:
%module test_module
%{
#include "test.h"
%}
%include <memory>
%ignore std::enable_shared_from_this<Test>;
%template(TestFromThis) std::enable_shared_from_this<Test>;
typedef std::enable_shared_from_this<Test> TestFromThis;
%include "test.h"
测试.py:
#!/usr/bin/env python3
import sys
import test_module
if __name__ == "__main__":
test = test_module.Test()
res = test.GetVal()
print("res={}".format(res))
sys.exit()
制作文件:
SWIG = /volume/evo/files/opt/poky/3.0.2-35/sysroots/x86_64-pokysdk-linux/usr/bin/swig4
CCX = g++
LD = g++
all: test_module.py
test_module.py: test.h test.cpp test_module.i
${SWIG} -python -py3 -c++ -cppext cpp -I/usr/include/c++/9 test_module.i
${CCX} -std=c++11 -O2 -fPIC -c test.cpp
${CCX} -std=c++11 -O2 -fPIC -c test_module_wrap.cpp -I/usr/include/python3.8
${LD} -shared test.o test_module_wrap.o -o _test_module.so
run: test_module.py
python3 ./test.py
clean:
rm -rf *~ test_module.py *_wrap.* *.o *.so __pycache__
编译时出现以下错误:
test_module.i:10: 错误:模板 'enable_shared_from_this' 未定义。
test.h:6:警告 401:对基类“std::enable_shared_from_this< Test >”一无所知。忽略。
test.h:6:警告 401:也许您忘记使用 %template 实例化“std::enable_shared_from_this< Test >”。
如果我删除所有出现的 std::enable_shared_from_this 它将毫无问题地工作。
通过添加虚拟 std::enable_shated_from_this 类并忽略它来解决它。
test_module.i:
%module test_module
%{
#include "test.h"
%}
%ignore std::enable_shared_from_this<Test>;
class std::enable_shared_from_this<Test> {};
%include "test.h"