【问题标题】:Using C++ code in a C program and Vice-Versa在 C 程序中使用 C++ 代码,反之亦然
【发布时间】:2023-03-19 19:21:01
【问题描述】:

我目前正在编写一个非常低级 C 程序与高级 C++ 程序之间的接口。它们的关联方式是通过链表:C 程序有一个链表,接口获取存储在链表中每个节点中的信息,并将其转换为 C++ 向量。该过程本身不是程序。问题是如何从 C 程序中调用该 C++ 函数。让我给你一些启示:

int importData(List *head, char * source, char * dest);

在名为import_helper.cpp 的C++ 文件中声明。我定义了声明,如上所示,然后是实现,所以编译不会抱怨。在 C 程序 import.c 中,我试图调用该函数:请记住,List 是在 import.c 中定义的结构 现在,在import.c 我有:

#if defined(_cplusplus)
extern 'C' {
#endif
typedef struct list{
   struct list *next
   .. other additional data goes here ...
}List;

int importData(List *head, char *source, char *dest);
#if defined(_cplusplus)
}
#endif

import_helper.cpp 标头中我做了一个#include "import.c"import.c 没有 .h 文件(有人写了那个代码,我个人认为这本身就是一个错误)。

当我编译时,我得到:

error: expected unqualified-id before 'class'
error: conflicts with the new declaration with 'C' linking
error: previous declaration of 'void getPassword(char *)' with 'C++' linkage 

这只是一个示例。但是,我相信import.c 是用gcc 编译的,而我的Build 文件用g++ 编译import_help.cpp。这可能是原因吗?我有其他类似方法的文件,所以我不太确定。任何想法? 谢谢

【问题讨论】:

  • 这似乎过于复杂。您可以轻松地从 C++ 调用 C 代码。为什么不将 C 函数封装在一个类中?
  • 因为 C 程序是为一项任务而设计的,而 C++ 代码是为另一项任务而设计的,但它们需要“交谈”
  • 重点是将C链表转换成C++向量。这很容易做到。该程序是如何从 C 程序调用该 C++ 函数,将该链表传递给 C++ 程序。
  • 那么,进程间通信是一种选择吗?否则,编写一个调用C++ 函数的extern C 函数。
  • 我想说,只要使用 g++ 就可以了(除非你使用它不理解的奇怪的 C99 东西?)。或者更仔细地管理你的头文件

标签: c++ c gcc g++ dynamic-linking


【解决方案1】:

解决方案是创建一个import_helper.h 文件,然后在import_helper.cpp 中将它包含在import_helper.cppimport.c 中(#include "import_helper.h")。 在import_helper.h 我有:

extern "C"{
   typedef struct list{
      ... /*some code goes here */
      struct list* next;
   }List;
   int importData(List *, char*, char*);
}

所以.c.cpp 共享相同的数据。

【讨论】:

    【解决方案2】:

    您可以通过在后端编写一个使用 C++ 的 DLL 在两个项目之间共享公共代码。只要声明是针对 C 进行的,您就应该能够从 C 或 C++ 程序调用定义的方法。

    【讨论】:

    • 这有两种extern方式:Liststruct用于C++函数,importData(List*, char*, char*)函数用于C程序。跨度>
    • 能否从 DLL 头文件中导出两者?
    • 您是将两个程序组合成一个可执行文件,还是使用 IPC 方法,例如共享内存对象?您需要在 C 中保留 importData 的定义,据我所知,您不能在该函数的主体中使用 STL 向量或“新”调用。您可以更改该函数以将 List* 复制到 import_helper 可访问的 List 的全局实例中吗?然后“发出信号” import_helper 以读取该实例并映射到 C++ 向量...
    【解决方案3】:

    当你在 .cpp 文件中定义 importData 时,你也需要把它放在一个 extern "C"(注意双引号)块中:

    extern "C"{
        int importData(List *head, char *source, char *dest){
            blah blah blah
            ...
        }
    }
    

    从错误中void getPassword(char *) 也需要它。

    【讨论】:

      【解决方案4】:

      C++ 可以抛出异常。

      确保您的 C++ 代码中的“C”接口捕获所有内容,并返回错误状态,并且可能返回某种类似 cstring 的消息,这样您就不会遇到任何意外的程序终止。

      【讨论】:

      • 你有 try/catch 来捕获所有异常吗?
      猜你喜欢
      • 2014-05-22
      • 2012-06-27
      • 1970-01-01
      • 1970-01-01
      • 2014-03-21
      • 1970-01-01
      • 2010-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多