memcpy指向炭缓冲区的指针

memcpy a pointer to a char buffer

本文关键字:指针 缓冲区 memcpy      更新时间:2023-10-16

我目前正在尝试一些不同的工作系统实现(根据本文进行(。

我要解决的问题是将论点传递给"工作函数"。

这是我的Job定义:

#define JOB_DATA_PADDING_SIZE   44
/** A job function is a function that can be worked on by the job manager */
typedef void( *JobFunction )( struct Job*, const void* );
/// <summary>
/// A job is something that represents work to be done by the thread pool.
/// Contains a pointer to it's work function and a counter to how many jobs
/// still need to be completed.
/// </summary>
struct Job
{
    JobFunction Function;                       // 8 byte
    Job* Parent;                                // 8 byte
    std::atomic<int32_t> UnfinishedJobs;        // 4 byte
    char Padding[ JOB_DATA_PADDING_SIZE ];      // 44 bytes, so that this object fills
                                                // a whole x64 cache line
};

如您所见,为了避免错误共享,有char Padding缓冲区需要在那里。我想将该缓冲区用作简单地存储需要传递给用户正在调用的JobFunction的参数的一种方式。此设置效果很好,除了一个例外:将指针作为参数。

用户创建作业时,他们在JobManager上调用此功能:

Job * JobManager::CreateJob( JobFunction aFunction, void* args, size_t aSize )
{
    assert( aSize >= 0 && aSize < JOB_DATA_PADDING_SIZE );
    Job* job = AllocateJob();
    job->Function = aFunction;
    job->Parent = nullptr;
    job->UnfinishedJobs.store( 1 );
    // Memcpy the args to the jobs padding
    if ( args != nullptr )
    {
        memcpy( job->Padding, args, aSize );
    }
    return job;
}

您可以看到,计划就是简单地memcpy用户在Padding中给出该函数的参数。这适用于诸如结构之类的事物,实际上是任何小于44字节大小的数据。

我想做的是 memcpy给定指针 Padding数组。但是,当我尝试此操作时,我遇到了memcpy在指针上复制该值的问题,然后将其复制到缓冲区中。

有没有办法可以将实际的指针 memcpy进入缓冲区?

我尝试使用uint64_tuintptr_t实验,但无济于事。

有办法做到这一点吗?我应该如何工作完全错误吗?

如果这也有助于提供更多上下文,则整个项目都在GitHub上。

有办法可以将实际指针记忆到缓冲区中?

当然。memcpy不在乎它的复制。它所做的只是将字节从源位置复制到目标位置。

假设您要复制int值。memcpy不知道int值。它只知道位置。因此,您将必须将值放入某个内存位置(例如,纳入int variable (,然后您可以给Memcpy一个指针。

extern void* destination_pointer;
int source = getIntValueFromWherever();          // put the value into the source location
size_t n_bytes = sizeof(source);
memcpy(destination_pointer, &source, n_bytes);   // then give memcpy a pointer to it.

但是您想复制指针。好吧,这是同样的交易。您要复制的东西(例如,某些foobar_t*指针(必须存储在一个位置(例如,在变量中(。然后,您将Memcpy指针转到来源和目的地位置。

与上面的int示例唯一不同的是source变量的数据类型:

extern void* destination_pointer;
foobar_t* source = getPointerFromWherever();     // put the value into the source location
size_t n_bytes = sizeof(source);
memcpy(destination_pointer, &source, n_bytes);   // then give memcpy a pointer to it.