c - 如何制作一个可以在不同代码库中重用的C "library"?

标签 c shared-libraries

我正在为学校开发一个项目,我认为我们可以在两个单独的项目中使用相同的代码。该代码本质上连接到主机上运行的套接字,该主机正在运行提供流量数据(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/

相关文章:

C 编译器访问全局 T const * const obj 的未定义行为,其底层对象可能会更改?

c - select() 函数不允许最后没有 "\n"的 printf()

c++ - 如何链接到运行时可能不存在的目录?

c - 在公共(public)头文件中包含条件是否被认为是好的做法?

c++ - 我可以在 Redhat Linux 机器上使用在 Ubuntu 上编译的共享库吗?

C 指针在执行期间奇怪地自增量为未知值

c - 值变成空字符串

mysql - ./configure 在树莓派 3 上找不到 libmysqlclient 库,无法链接

c - 在 ARM7TDMI 上获取参数地址时 GCC 是否损坏?

zend-framework - 确定服务器上安装的 zend 框架的版本