Bla*_*lly 3 scope class function arduino call
我刚刚开始在Arduino中创建库.我创建了一个名为inSerialCmd的库.我想在包含inSerialCmd库之后调用在主程序文件stackedcontrol.ino中定义的名为delegate()的函数.
当我尝试编译时,抛出一个错误:
...\Arduino\libraries\inSerialCmd\inSerialCmd.cpp:在成员函数'void inSerialCmd :: serialListen()'中:...\Arduino\libraries\inSerialCmd\inSerialCmd.cpp:32:错误:'委托'没有已经宣布
在进行了一些搜索之后,似乎添加范围解析运算符可能会成功.所以我在delegate()之前添加了"::",现在是":: delegate()",但是抛出了同样的错误.
现在我很难过.
您不能也不应该直接从库中调用程序中的函数.请记住使库成为库的关键方面:
库不依赖于特定的应用程序.可以将库完全编译并打包到.a文件中,而不存在程序.
所以存在单向依赖,程序依赖于库.乍一看似乎可能会阻止您实现您想要的效果.您可以通过有时称为回调的功能来实现您所询问的功能.主程序将在运行时向库提供指向要执行的函数的指针.
// in program somwehere
int myDelegate(int a, int b);
// you set this to the library
setDelegate( myDelegate );
Run Code Online (Sandbox Code Playgroud)
如果你看看如何安装中断处理程序,你会在arduino中看到这个.在许多环境中存在同样的概念 - 事件监听器,动作适配器 - 所有这些都具有允许程序定义库无法知道的特定操作的相同目标.
库将通过函数指针存储和调用该函数.这是一个粗略的草图,看起来像这样:
// in the main program
int someAction(int t1, int t2) {
return 1;
}
/* in library
this is the delegate function pointer
a function that takes two int's and returns an int */
int (*fpAction)(int, int) = 0;
/* in library
this is how an application registers its action */
void setDelegate( int (*fp)(int,int) ) {
fpAction = fp;
}
/* in libary
this is how the library can safely execute the action */
int doAction(int t1, int t2) {
int r;
if( 0 != fpAction ) {
r = (*fpAction)(t1,t2);
}
else {
// some error or default action here
r = 0;
}
return r;
}
/* in program
The main program installs its delegate, likely in setup() */
void setup () {
...
setDelegate(someAction);
...
Run Code Online (Sandbox Code Playgroud)