gpt4 book ai didi

c++ - 从 const void * 转换为 float 数组

转载 作者:太空狗 更新时间:2023-10-29 23:53:33 26 4
gpt4 key购买 nike

我正在为 mbed 平台使用 rtos 库。我希望能够跳入线程,以恒定的速率递增某个值,然后在结束时关闭线程。问题在于,从 mbed RTOS 库实现 Thread 的方法只能采用 const void * 参数。这没什么大不了的,除非我需要向它发送一个浮点值数组,其中一个值是指向我需要递增的值的指针(*joint),而其他值可以简单地是 const 控制增量的范围和速度。我以为我已经控制住了它并在这里找到了一些整洁的代码来正确地转换,但我仍然不断提出 0 值://float (*vals)[4] = (float (*)[ 4])参数;

这是代码,简化为参与线程工作的两个函数。

void increment( void const *args ) { //float *joint, float inc, float target, int speed ) 
//float (*vals)[4] = (float (*)[4])args;
float *vals = (float* )args;

// joint is the outside value I want to increment
float *joint = &vals[0];
float inc = vals[1];
float target = vals[2];
int speed = (int)vals[3];
float start = 0.5;


if( inc < 0 )
for( *joint = start; *joint > target; *joint+=inc ) {
wait( 0.1 / speed );
}
}


void thread_inc( float *joint, float inc, float target, int speed ){
float args[4] = { *joint, inc, target, (float)speed };
//Thread move( increment, args );
Thread move( increment, &args );
return;
}

预先感谢您为我指明正确方向的任何事情!

最佳答案

我绝对是从 jlunavtgrad、Pat 和 Burton Samograd 那里偷来的。我觉得他们的所有三个答案都真正回答了 OP。

  1. 使用表示要传递给新线程上下文的参数的结构可以更好地管理。

  2. args 数组在堆栈上并受thread_inc 范围的限制。通过用结构替换它,您仍然无法解决此处涉及的范围问题。因此,需要以其他线程上下文可以正确使用它们的方式分配参数(以任何形式)——这可以通过全局或堆来完成。

  3. thread_incfloat *joint 参数被解除引用,该值用于填充参数。这似乎不是所需的行为,因为只会修改参数数组中复制的值。

代码中的建议修改:

struct thread_args {
float * joint;
float inc;
float target;
int speed;
};


void increment( void const *args ) {
thread_args* threadArgs = static_cast<thread_args*>( args );

float *joint = threadArgs->joint;
float inc = threadArgs->inc;
float target = threadArgs->target;
int speed = threadArgs->speed;
float start = 0.5;

if( inc < 0 ){
for( *joint = start; *joint > target; *joint+=inc ) {
wait( 0.1 / speed );
}
}

delete threadArgs;
}

void thread_inc( float *joint, float inc, float target, int speed ){
thread_args* threadArgs = new thread_args;
threadArgs->joint = joint;
threadArgs->inc = inc;
threadArgs->target = target;
threadArgs->speed = speed;

//Thread move( increment, args );
Thread move( increment, threadArgs );
return;
}

与此解决方案相关的最后一个建议是,不要以原始形式使用 newdelete,而是使用某种智能指针,例如 shared_ptr

关于c++ - 从 const void * 转换为 float 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10387496/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com