这个问题是关于 C++ 的,但它与 Arduino 交互,由于我不是软件开发人员,我很乐意得到一些建议。
在 Arduino 中,用户创建一个类的实例并设置其委托(delegate)方法:
Arduino main program:
//instance
Main interpreter;
//set delegate
interpreter.setDelegate(intepreterDelegate);
//delegate function
float intepreterDelegate(char *arg){return 3;}
Main
类,然后创建另一个类的实例,称为 Sub
,因此:
Sub - > send delegate to Main-> send delegate to Arduino
Main
类成功获取来自 Sub 的委托(delegate)消息:
Main.h
//being called from the sub
static float fromSubDelegate(char *arg){
// *Here I am trying to push forward this delegate out to the user on arduino
Main. b;
float result = (b.*b.fpAction)(arg);
return result;
};
float (Main.::*fpAction)(char*) = 0 ;
void setDelegate( float(*fp)(char*));
问题出在我设置委托(delegate)的 Main.cpp
上
//arduino set this delegate of the main class .cpp
void Main.::setDelegate( float(*fp)(char*))
{
fpAction = fp; // *gives error because fpAction is a member function
}
我已经提供了所有的数据。我不是 C++ 程序员,因此我可能做错了什么。
最佳答案
这不是您在另一个问题中真正提出的问题。 你(似乎)在 adruino 代码中所做的不匹配 以及您在 C++ 代码中想要什么。
您不能将您的委托(delegate)从非成员函数更改为成员函数 和 您在它使用的类之外定义一个成员函数(即委托(delegate))。
您正在尝试的目前没有意义。 你的arduino定义了一个实例
Main interpreter;
然后它在解释器实例中定义并设置委托(delegate)(到目前为止还可以)。
但是在 fromSubDelegate() 中你创建了一个新的实例 b。 无论您在解释器实例中设置的哪个委托(delegate)都不会在 b 实例中设置,除非函数指针是静态的,但在这种情况下您甚至不需要 fromSubDelegate() 函数,您可以调用函数指针直接。
您似乎对事物的运作方式有错误的认识。要带回家的是,如果您有一个类的非静态成员函数,则有一个隐藏的额外参数,您可以在函数中将其用作“this”。 所以你定义一个成员函数
class X
{
void func(int i);
}
和
不一样void func (int i);
在类之外定义。确实更像void
func(X* this, int i);
虽然这在语义上是“正确的”,但在句法上却不正确。
关于c++ - 将函数指针从 Arduino 传递到 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38766190/