[英]How do I pass a function with a fixed parameter to another method in C?
Suppose I have a print Function which takes a void* as an argument: 假设我有一个print函数,它以void *作为参数:
Print(void *instance)
How can I Set the member of a struct to this method? 如何将结构的成员设置为此方法?
struct Foo
{
void(*Print)(); //this does not match to Print above!
//void(*Print)(void* Instance); //This would but I cannot change this
}
So how would I have to change this method: 因此,我将如何更改此方法:
void Init()
{
struct Foo* k = malloc(sizeof(Foo));
Foo->Print = &Print(k); //does not work?!
//Foo->Pring = &Print; //would work if types were the same
}
I want to set a function pointer inside a struct with a Fixed argument. 我想在带有固定参数的结构内设置函数指针。
Basically this is a way to implement object oriented code in ANSI-C. 基本上,这是在ANSI-C中实现面向对象代码的方法。 The source project is this: Object Orientation in C?! 源项目是这样的: C语言中的对象定向?
This would be about changing this piece of C Code: 这将与更改这段C代码有关:
String* r = New_String("Hello");
r->Free(r); //this works
r->Free(); //this is how it should be!
So that the instance does not have to be passed to the methods themselfes. 这样就不必将实例传递给方法本身。
Summarized : Goal is to get the Foo instance inside Print called like Foo->Print(); 总结 :目标是在Print内获取Foo实例,如Foo-> Print();。
With: 带有:
Foo->Print = &Print(k);
you are assigning a function pointer and you are "calling" the function with a parameter. 您正在分配一个函数指针, 并且正在使用一个参数“调用”该函数。 That is wrong. 那是错的。 What you can do is: 您可以做的是:
Foo->Print = Print;
Foo->Print = (void(*)())Print; // if compiler complains, use a cast
Because Print
is a function, the compiler will use its address when assigning it to the function pointer field of the struct. 因为Print
是一个函数,所以编译器在将其分配给该结构的函数指针字段时将使用其地址。 But because your Print
function is incompatible with the Print
field, you must use a cast to silence the compiler. 但是,由于您的Print
函数与Print
字段不兼容,因此必须使用强制转换使编译器静音。 Your Print
function is casted to a "function that can take any number of parameters". 您的Print
功能强制转换为“可以接受任何数量的参数的功能”。 The casting is safe here as long as you call it with at least one parameter. 只要您使用至少一个参数进行调用,此处的转换都是安全的。 Only do this casting when you know what you are doing, or undefined behavior will follow. 仅当您知道自己在做什么时才执行此强制转换,否则将发生未定义的行为。
Once the function pointer is assigned, you can now call it with your parameter: 分配完函数指针后,您现在可以使用参数进行调用:
Foo->Print(k);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.