Rot*_*er2 0 c alias function clang freestanding
我想创建一个函数来选择C中的另一个,也许这个C伪代码可以帮助澄清我想要的东西:
void set_method(const char *method)
{
// Check if the method is serial_port
if (strcmp(method, "serial_port") == 0)
{
// assign the alias "print" to serial_print
// something like defing here a function like this:
// print(const char *print) { serial_print(print); }
print(const char *print) = serial_print(const char *message)
}
else if (strcmp(method, "graphical_tty") == 0)
{
// The same that serial_port case but with graphical_tty_print
}
else
{
// Error
}
}
Run Code Online (Sandbox Code Playgroud)
目标是在满足条件时为函数分配"别名",我该怎么做?
我正在使用一个独立的C实现,用clang编译.
看起来你正在寻找函数指针.请参阅以下代码,其中介绍了一种要调用的函数,一个指向该类型函数的全局指针,以及根据您的逻辑分配适当函数的代码:
typedef int (*PrintFunctionType)(const char*);
int serial_print(const char *message) { printf("in serial: %s\n", message); return 0; }
int tty_print(const char* message) { printf("in tty: %s\n", message); return 0; }
PrintFunctionType print = serial_print; // default
void set_method(const char *method)
{
// Check if the method is serial_port
if (strcmp(method, "serial_port") == 0) {
print = serial_print;
}
else if (strcmp(method, "graphical_tty") == 0) {
print = tty_print;
}
else {
// Error
}
}
int main() {
print("Hello!");
set_method("graphical_tty");
print("Hello!");
}
//Output:
//
//in serial: Hello!
//in tty: Hello!
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你 :-)
| 归档时间: |
|
| 查看次数: |
62 次 |
| 最近记录: |