我正在为学校开发一个项目,我认为我们可以在两个单独的项目中使用相同的代码。该代码本质上连接到主机上运行的套接字,该主机正在运行提供流量数据(x、y 位置)的模拟器。这些位置被解析为一个结构体:
struct Vehicle{
Double x;
Double y;
int id;
int type;
}
这些结构的列表将返回到实例化该库的程序。所以我想采用这段代码,我必须解析数据并有一个通用方法,可以在每个事件后(大约每 1 毫秒)将结构传递回调用者。我该如何去做呢?
更新:
我不清楚的部分是让库每隔x
秒获取数据,然后将该数据传递到另一个相应更新的文件。因此,如果 fileA
是绘制位置的代码,而 fileB
负责将数据解析为结构,那么我将如何在 fileA< 中的方法中更新 Canvas
通过从 fileB
传回数据(而不是调用 fileB 中的某些方法来获取数据)。
最佳答案
how would I update the canvas in methods in fileA by passing the data back from fileB (as opposed to calling some method in fileB to get the data).
每次 fileB 中的数据准备就绪时,fileB 中的代码需要调用 fileA 中的方法,并使用调用的方法将数据传递到 fileA 中。
所调用的 fileA 方法可以是硬编码的(始终相同),或者在启动时 fileA 中的代码可以调用 fileB 方法,传递每当数据准备好时 fileB 应该调用的函数 - 这称为“注册回调”
我不确定你会如何用 C 语言做到这一点(自从我使用该语言以来已经很多年了)。在 C++ 中,它是相当标准的,如下所示:
#include <iostream>
#include <functional>
#include <thread> // std::this_thread::sleep_for
#include <chrono> // std::chrono::seconds
using namespace std;
class B;
class A
{
public:
// function that should be called when data is ready
void Callback();
void Register( B& theB );
};
class B
{
public:
void RegisterCallback( function<void(void)> f );
// method that runs whenever new data is ready
void SendDataToA();
function<void(void)> myCallback;
};
void A::Register( B& theB )
{
theB.RegisterCallback( [this]()
{
Callback();
} );
}
void A::Callback()
{
// B has sent some data
cout << "A::Callback\n";
}
void B::RegisterCallback( function<void(void)> f )
{
myCallback = f;
}
void B::SendDataToA()
{
while( 1 ) {
std::this_thread::sleep_for (std::chrono::seconds(1));
// data is ready, send it to A
myCallback();
}
}
int main()
{
A theA;
B theB;
// register A's callback with B
theA.Register( theB );
// run B's data pump
theB.SendDataToA();
return 0;
}
关于c - 如何制作一个可以在不同代码库中重用的C "library"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60103346/