I am trying to call a function defined in the parent class via the object. But I am getting the error a pointer to member is not valid for a managed class. How can I achieve what I wanted? My expected output is to display the text "Called from child"
MyChild.h
ref class MyChild
{
System:Void(\*my\_func\_ptr)(int, char\*);
typedef System:Void(\*MyFuncPtrType)(int, char\*);
MyFuncPtrType my\_func\_ptr;
public: MyChild ( System:Void(\*some\_func)(int, char\*)){
my\_func\_ptr = some\_func;
}
public: System::Void Child\_ButtonClicked(System::Object^ sender, System::EventArgs^ e){
my\_func\_ptr();
}
}
MyForm.h
#include "MyChild.h"
public ref class MyForm : public System::Windows::Forms::Form
{
.
.
.
private: static System:Void test(int, char*) { //Update
MessageBox::Show("Called from child");
}
private: System::Void MyForm::MyForm\_Load(System::Object^ sender, System::EventArgs^ e) {
MyChild^ child= gcnew MyChild( **MyForm::test**); **//type incompatible error in this line**
child -> test(1,"random");
}
}
Update 2, Previous problem for //type incompatible error in this line is solved using the following way below.
MyChild.h
ref class MyChild
{
private: System::Void(\*my\_func\_ptr)(int, char\*);
public: System::Void doFunction(int A, char\* B) {
(\*my\_func\_ptr)(A,B);
}
public: MyChild ( System::Void(\*func)(int A, char\* B)){
my\_func\_ptr = func;
}
public: System::Void Child\_ButtonClicked(System::Object^ sender, System::EventArgs^ e){
doFunction(1,"random"); //the arguments here are not used in later program, it is just for testing a function ptr with arguments
}
}
MyForm.h
#include "MyChild.h"
public ref class MyForm : public System::Windows::Forms::Form
{
.
.
.
typedef System::Void (\*callback\_function)(int, char\*);
private: static System:Void test(int, char\*) {
MessageBox::Show("Called from child");
}
private: System::Void MyForm::MyForm\_Load(System::Object^ sender, System::EventArgs^ e) {
callback\_function disc;
disc = (callback\_function)(MyGUI::MyForm::test);
MyChild^ child= gcnew MyChild( **disc**);
child -> doFunction(1,"random");
}
}
For now, everything is solved but I am still unsure to the reason for incompatibility for argument and parameter having same type. I will do more trails and see if this is a stable