作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我试图在winapi上写一个包装器。我想包装接受回调函数指针的函数。
例如,考虑以下情况:
// The unsafe callback type the FFI function accepts
type UnsafeCallback = unsafe extern "system" fn(exception_info: *mut ExceptionInfo) -> u32;
// The safe callback type my function should accept
type SafeCallback = fn(exception_info: &ConvertedExceptionInfo) -> u32;
将使用的功能:
// The function exposed by winapi
unsafe extern "system" fn SetExceptionHandler(handler: UnsafeCallback);
// The function I want to expose in my library
fn SetExceptionHandler(handler: SafeCallback);
我想创建一个包装函数,如下所示:
unsafe extern "system" fn(exception_info: *mut ExceptionInfo) -> u32 {
let result = panic::catch_unwind(|| {
// Convert ExceptionInfo into ConvertedExceptionInfo. I know this is undefined behavior, but its only here
// to demonstrate program flow
let converted_exception_info: ConvertedExceptionInfo = (*exception_info).into();
// Call the corresponding safe function (as to how we get the function pointer here, that's
// the whole question)
return safe_callback(&converted_exception_info);
});
return match result {
Ok(val) => val,
Err(_) => _
};
}
我可以想到两种创建包装函数的可能性:
SetExceptionHandler
方法。SetExceptionHandler
函数以接受UnsafeCallback
类型。最佳答案
经过大量搜索之后,我发现了一篇博客文章,该文章为包装回调问题提供了一个很好的解决方案。 Article here
关于windows - 如何安全包装回调传递给Windows FFI?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62565082/
我是一名优秀的程序员,十分优秀!