儘管沒有真正的方法可以直接驗證數據是否屬於特定類型,但我已經設定了一種方法來'推測'該類型匹配。
這並不是100%保證它是指定的類型。但是,它會假定它基於類型代碼。
我也添加了一些測試。我在幾分鐘內寫了這篇文章,所以我確信它有改進的空間,而且我絕不是本地開發人員。我只是有需要而已。如果它幫助某人,真棒!
#include <stdio.h>
#include <stdlib.h>
// Type Definitions
// These are the type definitions that can be used to check for type
// They need to be unique so that only types starting with these
// prefixes will be presumed to be of the type specified.
typedef enum type {
TYPE_StateRequester = 0x10f3ccd3,
TYPE_OtherThing = 0x09331c8c
} type;
// State Requester Definitions & Functions
typedef int state_requester_f(void* request_parameters);
// Since we want to check the "type" of a function reference,
// we need to wrap it in a struct along with it's type code.
struct state_requester_t {
int type;
state_requester_f* call;
} typedef state_requester_t;
state_requester_t new_state_requester(state_requester_f* call) {
state_requester_t sr;
sr.type = TYPE_StateRequester;
sr.call = call;
return sr;
}
// This function will check if data is of type StateRequester
//
// If the data sent to this function is not of the length
// nessecary for the state_requester type, - OR -
// it's type property is not equal to the StateRequester type
// then we will presume that this data is NOT of type StateRequester
uint8_t is_state_requester(void* data, size_t len) {
return len == sizeof(state_requester_t) &&
((state_requester_t*)data)->type == TYPE_StateRequester;
}
// Testing functions
int test_caller(void* data) {
printf("Got to the test_caller function.\n");
return 0;
}
int main(int agc, char *argv[]) {
// Create an actual state_requester_t definitiion
state_requester_t sr = new_state_requester(&test_caller);
// Test to see if it's validated as a state_requester_t
if (is_state_requester(&sr, sizeof(state_requester_t))) {
printf("Yes, variable 'sr' is presumadely of type state_requester_t\n");
sr.call(NULL);
} else {
printf("No, variable 'sr' is not of type state_requester_t\n");
}
// Create a phony state_requester_t definition,
// but keep it the same length as a regular
// state_requester_t
void* a = malloc(sizeof(state_requester_t));
// Test to see if it's validated as a state_requester_t
if (is_state_requester(a, sizeof(state_requester_t))) {
printf("Yes, variable 'a' is presumadely of type state_requester_t\n");
} else {
printf("No, variable 'a' is not of type state_requester_t\n");
}
free(a);
// Create a phony state_requester_t with an improper length
void* b = malloc(5);
// Test to see if it's validated as a state_requester_t
if (is_state_requester(b, sizeof(state_requester_t))) {
printf("Yes, variable 'b' is presumadely of type state_requester_t\n");
} else {
printf("No, variable 'b' is not of type state_requester_t\n");
}
free(b);
return 0;
}
C沒有這種能力。類型在編譯時檢查 –
順便說一句,'請求者'不是'state_requester'類型。 '請求者'是類型'state_requester *'。 – chux
...但另一方面,類型*在編譯時檢查。這樣的檢查可以被任意地覆蓋或者可以忽略它們的結果,但是不像有人調用你的函數可能會意外地傳遞錯誤類型的參數,而沒有任何機會發現它們的錯誤。 –