简体   繁体   English

Arduino-在草图中使用的C库中包含SD.h

[英]Arduino - Including SD.h within a C library used in sketch

I am working on compiling a certain C library for the Arduino Mega2560. 我正在为Arduino Mega2560编译特定的C库。 However, I need access to the SD.h library from within my C library. 但是,我需要从我的C库中访问SD.h库。 Is this possible if I write a C++ to C wrapper? 如果我将C ++编写为C包装器,这可能吗?

Other relevant material: 其他相关材料:

calling c++ code from c http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html 从c http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html 调用c ++代码

You should just be able to write a wrapper library with a C interface, that calls the C++ library. 您应该只能够编写带有C接口的包装器库,该包装器调用C ++库。

The key here is using extern "C" when building as C++ to ensure the C++ parts call the C functions as C and not C++. 此处的关键是在构建为C ++时使用extern "C" ,以确保C ++部分将C函数称为C而不是C ++。

The SD header is more complicated to wrap than, for example, Serial.h as you need to return and wrap the File objects as well. SD标头的包装要比Serial.h复杂,因为您还需要返回并包装File对象。 This can be done using a struct declaration in the header, with the real type defined in the .cpp . 这可以通过在标头中使用struct声明以及.cpp中定义的实数类型来完成。 By working only with pointers to this type in the header, you don't need to define the struct at this point. 通过仅在标头中使用指向该类型的指针,您无需在此时定义结构。 You could alternatively use void* pointers, but I would avoid this as you loose type safety. 您也可以使用void*指针,但是当您失去类型安全性时,我会避免这种情况。

SD_c_iface.h SD_c_iface.h

#ifndef SD_C_IFACE_H
#define SD_C_IFACE_H

#include <Arduino.h>

#ifdef __cplusplus
extern "C" {
#endif

/* Wrapper around File type */

typedef struct _SD_File SD_File;

size_t SD_File_write(SD_File* file, const uint8_t *buf, size_t size);

/* TODO Wrap all required File functions */

/* Wrapper around SD type */

boolean SD_begin(uint8_t csPin);

void SD_open(const char *filename, uint8_t mode, SD_File** file);

/* TODO Wrap all required SD functions */

#ifdef __cplusplus
}
#endif
#endif

SD_c_iface.cpp SD_c_iface.cpp

#include "SD_c_iface.h"

#include "SD.h"

struct _SD_File
{
  File f;
};

size_t SD_File_write(SD_File* file, const uint8_t *buf, size_t size)
{
  return (file) ? file->f.write(buf, size) : 0;
}

boolean SD_begin(uint8_t csPin)
{
  SD.begin(csPin);
}

void SD_open(const char *filename, uint8_t mode, SD_File** file)
{
  if (!file)
    return;
  *file = new _SD_File();
  (*file)->f = SD.open(filename, mode);
}

// TODO Add more function wrappers

The method above is the generic way to wrap things, in your case you could, for example simplify things and only allow a single file to be opened at once, as the SD.h library only allows one open at once. 上面的方法是包装事物的通用方法,例如,您可以简化事物并只允许一次打开一个文件,因为SD.h库只允许一次打开一个文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM