Arduino esp8266中的c++函数修改了c文件中生成的 float ,c++函数退出后在c文件中看到乱码

标签 c++ c azure arduino-esp8266

我正在为 Azure IoT 中心编写代码,这需要在 Arduino 循环 () 中使用 c 函数。我遇到的问题是,如果我将 c 文件中创建的 float 的指针传递给 c++ 文件并修改该值,则 c++ 函数返回后在 c 文件中看到的内容是乱码。

这是一个伪代码示例,下面包含一个工作示例:

ino 文件中的

loop():
运行 runInLoop(),在 c 文件 RunTest.c 中定义

RunTest.c 中的 runInLoop():
创建一个 float
将地址传递给FloatTest.cpp中定义的modifyFloat(float *address)
在modifyFloat()返回后打印 float 的值。

FloatTest.cpp中的modifyFloat(float *address):
为 *address
分配一个值 打印值
返回

我在下面的工作示例中执行了这个伪代码,串行监视器中的结果是:

Value assigned in modifyFloat: 22.55
The value that was returned is: 1077316812

我正在使用 Adafruit Huzzah Feather,其配置完全按照文档中的指示进行。

这是一个工作示例:

azure_troubleshoot.ino

#include "RunTest.h"

void setup()
{
    initSerial();
}

void loop()
{
    Serial.println("Starting main loop!\r\n");
    runInLoop();
}

void initSerial()
{
    Serial.begin(9600);
}

运行测试.c

#include "FloatTest.h"

void runInLoop(void)
{
    while(1)
    {
        float testValue;
        modifyFloat(&testValue);
        (void)printf("The value that was returned is: %d\r\n", testValue);
        delay(1000);
    }

}

运行测试.h

#ifndef RUNTEST_H
#define RUNTEST_H

#ifdef __cplusplus
extern "C" {
#endif

void runInLoop(void);

#ifdef __cplusplus
}
#endif

#endif // RUNTEST_H

FloatTest.cpp

#include <Arduino.h>
#include "FloatTest.h"

void modifyFloat(float *address)
{
    *address = 22.55;
    Serial.print("Value assigned in modifyFloat: ");
    Serial.println(*address);
}

FloatTest.h

#ifndef FLOATTEST_H
#define FLOATTEST_H

#ifdef __cplusplus
extern "C" {
#endif

void modifyFloat(float* address);

#ifdef __cplusplus
}
#endif

#endif // FLOATTEST_H

最佳答案

问题是在 RunTest.c 的 printf 字符串中使用了 %d。将代码更新为如下所示可以修复问题并生成输出:

Value seen in modifyFloat: 22.55
The value that was returned is: 22.55

运行测试.c

#include "FloatTest.h"

void runInLoop(void)
{
    while(1)
    {
        float testValue;
        modifyFloat(&testValue);
        char str_tmp[6];
        dtostrf(testValue, 4, 2, str_tmp);
        (void)printf("The value that was returned is: %s\r\n", str_tmp);
        delay(1000);
    }

}

关于Arduino esp8266中的c++函数修改了c文件中生成的 float ,c++函数退出后在c文件中看到乱码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41726934/

相关文章:

c++ - 将 cout 格式对齐为表格的列

c++ - 是否可以返回指向类中声明的结构的指针?

c++ - 为什么operator delete的签名要带两个参数?

c - 在原始套接字上获取以太网帧长度(非阻塞)

Azure EventHubs EventProcessorHost 尝试访问 Azure 存储队列

c# - 如何使用 Azure IoT 中心 SDK 从 Azure IoT 中心设备接收消息到 C# 控制台应用程序

Azure 存储帐户备份(表和 blob)

c++ - Visual Studio 中的 std::begin 和 std::end 迭代器

c - 循环遍历 C 中的一系列 float

c - strtok 中的可变长度