Reputation: 1
pub fn test_set_callback() -> i32 {
static TEST_THREAD: OnceLock<CfntestSetCallback> = OnceLock::new();
let callbacks = Callbacks::new();
//use static
// unsafe { TEST_THREAD.get_or_init(|| get_prometheus_lib().get(b"test_set_callback").unwrap() as CfntestSetCallback)(&callbacks) }
//not use static
// unsafe { (get_prometheus_lib().get(b"test_set_callback").unwrap() as CfntestSetCallback)(&callbacks) }
1
}
In the above trust code, when I use the line of ‘use static’, the callbacks are not released after the end of the function test_set_callback, but when I use the line of ‘not use static’, the callbacks are released after the end of the function test_set_callback. What is the reason? Here are the relevant codes:
use libloading::Library;
use std::sync::OnceLock;
use crate::common::config::AppConfig;
pub fn get_prometheus_lib() -> &'static Library {
static PROMETHEUS_LIB: OnceLock<Library> = OnceLock::new();
PROMETHEUS_LIB.get_or_init(|| unsafe { Library::new(AppConfig::get_app_config().file_lib_prometheus).unwrap() })
}
#[allow (non_snake_case)]
#[allow (non\u camel\u case\u types)]
type CBFunc_Test_Fn = unsafe extern "C" fn(p: libc::c_int);
#[allow (non_snake_case)]
#[allow (non\u camel\u case\u types)]
type CBFunc_Market_OnRtnDepthMarketData = unsafe extern "C" fn(p: *const CBP_Market_OnRtnDepthMarketData);
#[repr (c)]
#[allow (non_snake_case)]
#[allow (non\u camel\u case\u types)]
pub struct Callbacks {
pub CBFunc_Test_Fn: Option<CBFunc_Test_Fn>,
pub CBFunc_Market_OnRtnDepthMarketData: Option<CBFunc_Market_OnRtnDepthMarketData>,
}
type CfnTestThread = Symbol<'static, unsafe extern "C" fn() -> libc::c_void>;
type CfntestSetCallback = Symbol<'static, unsafe extern "C" fn(*const Callbacks) -> libc::c_int>;
Test_set_callback is the c++export Library:
Callbacks *callback = nullptr;
LIB_CTP_EXPORT int test_set_callback(Callbacks *cb_callback) {
if (cb_callback == nullptr) {
}Else{
callback = cb_callback;
}
return 2;
}
I dont understand why it happens The reason why I am so convinced of this issue is that I started a thread in C++that keeps polling for callback objects, like this:
Callbacks *callback = nullptr;
....
void test_thread_fn() {
while (true) {
if (callback != nullptr) {
auto v = new CBP_Market_OnRtnDepthMarketData(nullptr);
if (callback->CBFunc_Market_OnRtnDepthMarketData != nullptr) {
callback->CBFunc_Market_OnRtnDepthMarketData(v);
} else {
std::cout << "test_thread_fn CBP_Market_OnRtnDepthMarketData is null" << std::endl;
}
delete v;
}
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
}
LIB_CTP_EXPORT void run_thread() {
std::thread t(test_thread_fn); // 启动线程并执行 taskFunction
t.detach();
}
Upvotes: 0
Views: 46