[英]pointer function returning value issue
我最近正在開發一個 C 解決方案,我使用函數指針來模擬發生事件時的回調行為。
我很好地考慮了這種 c 語言能力。 在我的整個程序中使用它。 但我仍然不明白一些行為。
我有一個函數,我返回一個 int,假設為 4。我在該函數上放置了一個指針並將其分配給結構中的一個變量。 然后將該結構傳遞給一個函數,其中我有一個結構類型的全局變量,該變量等於我的回調結構。
到目前為止一切順利,但是當我使用它自己的回調來檢索 4 的 int 值時,它返回一個錯誤的值,看起來像一個未初始化的值,或者命中了錯誤的內存段。
回調是在一個線程中調用的,但它不是來自線程池,而是只有一個線程循環來檢索信息並將其傳遞給服務器端。 所以他們沒有並發訪問變量。
給你一個我的實現的直觀例子:
這是回調聲明
gboolean zeta_transport_is_api_secret_needed(janus_transport *plugin);
gboolean zeta_transport_is_api_secret_valid(janus_transport *plugin, const char *apisecret);
gboolean zeta_transport_is_auth_token_needed(janus_transport *plugin);
gboolean zeta_transport_is_auth_token_valid(janus_transport *plugin, const char *token);
int zeta_transport_get_server_load();
static zeta_transport_callbacks zeta_handler_transport =
{
.incoming_request = zeta_transport_incoming_request,
.transport_gone = zeta_transport_gone,
.is_api_secret_needed = zeta_transport_is_api_secret_needed,
.is_api_secret_valid = zeta_transport_is_api_secret_valid,
.is_auth_token_needed = zeta_transport_is_auth_token_needed,
.is_auth_token_valid = zeta_transport_is_auth_token_valid,
.get_server_load = zeta_transport_get_server_load,
};
我在其中聲明函數指針的頭文件 transport.h :
struct janus_transport_callbacks {
...
int (* const get_server_load)();
}
這是我調用傳輸層的 init 函數:
janus_transport->init(&zeta_handler_transport, configs_folder);
傳輸層初始化函數:
int janus_websockets_init(zeta_transport_callbacks *callback, const char *config_path) {
if(g_atomic_int_get(&stopping)) {
/* Still stopping from before */
return -1;
}
if(callback == NULL || config_path == NULL) {
/* Invalid arguments */
return -1;
}
/* This is the callback we'll need to invoke to contact the gateway */
gateway = callback;
/* I then call the thread where the callback will be called to retrieve the integer of 4 */
g_thread_try_new("Client_start", Client_start, NULL, NULL);
一旦線程在這里啟動,我就是如何調用“CallBack”的
int ret = gateway->get_server_load;
printf(KRED"Server load = %d .\n"RESET, ret);
最后是輸出:
Server load = 4416800 .
我仍在獲取,但我真的好幾天都看不到我的錯誤。
你忘了打電話給你的回調。 改變
int ret = gateway->get_server_load;
到
int ret = gateway->get_server_load();
// ^^^^
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.