我目前正在使用pybind11来生成cpp-python接口.我有一个回调函数,如下
Pyind_回调.h
#pragma once
#include <stdint.h>
#include <functional>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/functional.h>
namespace py = pybind11;
typedef std::function<void(uint32_t, uint32_t)> tCbType;
void pybind_add_cb(tCbType func);
Pyind_allback.cpp
#include "Pyind_回调.h"
#include <vector>
static std::vector<tCbType> cb_func{};
void pybind_add_cb(tCbType func)
{
cb_func.push_back(func);
}
我的pybind11绑定实现如下
Main.cpp
#include <pybind11/pybind11.h>
#include "Pyind_回调.h"
namespace py = pybind11;
PYBIND11_MODULE(pybind_interface, m) {
m.def("pybind_add_cb", &pybind_add_cb, "");
}
生成的文件是pyind_allback.so,我将其导入以供在我的python单元测试中使用,如下所示
Test.py
import unittest
from pybind_interface import *
class TestPyBind11(unittest.TestCase):
def setUp(self):
self.cb_count = 0
print("Starting test!")
def cb_func(self, start, end):
print(f"cb_func(start=0x{start:08x}, end=0x{end:08x})")
self.cb_count += 1
def test_callback(self):
pybind_add_cb(lambda start,end: self.cb_func(start, end))
#=================================================================
if __name__ == '__main__':
unittest.main()
尽管测试成功运行并在测试通过后返回"OK",但在unittest框架的main.py中的sys.exit(not self.result.wasSuccessful())
行中停留了一段时间.我已经验证了self.result.wasSuccessful()
返回1,并且它应该得到一个sys.exit(0),然后它应该优雅地退出.但这并没有发生.我得到的结果如下
Starting test!
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
*stuck at this point*
但在上面的情况下,Python从未退出,并停留在调用sys.exit(0)
的时候.如果我在unittest函数中强制将sys.exit(0)
更改为os._exit(0)
,则它将正确退出.这是我的全部代码.这个实现可以通过swg实现,但我不想使用它,因为语法很难.
有人知道为什么会发生这种事吗?
我希望unittest在遇到sys.exit(0)时正常退出.但即使测试通过,