在C和C++库之间共享变量的困境

Sharing a variable between C and C++ libraries dilemma

本文关键字:共享变量 困境 之间 C++      更新时间:2023-10-16

我有一个简单的问题。我有两个库,一个用C编译,另一个用C++编译,其中C库由C++库链接和加载。我需要在C库中声明一个既可以读写的结构实例。你是如何做到这一点的?

感谢

EDIT:添加了它将是一个结构的实例,而不仅仅是声明

您需要创建一个单独的头文件,该文件由C和C++库中的模块包括:

#ifndef YOURSTRUCT_H
#define YOURSTRUCT_H
#ifdef __cplusplus
extern "C" {
#endif
    struct YourStruct
    {
        // your contents here
    };
#ifdef __cplusplus
}
#endif
// UPDATE: declare an instance here:
extern YourStruct yourInstance;
#endif

这种形式的头文件意味着两个编译器都会很乐意读取头文件,并且都会产生相同的名称篡改。

更新:
然后您需要一个模块文件。就这一个。如果要包含在您的C库中,请选择C文件;如果要包含到您的C++库中,则选择C++文件:

#include "yourstruct.h"
YourStruct yourInstance;

现在,全局实例的任何客户端,无论是C客户端还是C++客户端,都必须使用#include "yourstruct.h"并引用yourInstance

更新:
正如Matthieu所指出的,你最好把指针传给周围的实例。例如

#include "yourstruct.h"
#ifdef __cplusplus
extern "C" {
#endif
void yourFunction(YourStruct* someInstance);
#ifdef __cplusplus
}
#endif

使用外部C链接规范。

#ifdef __cplusplus 
extern "C" {
#endif 
    struct YourStruct
    {

    };
#ifdef __cplusplus 
}
#endif 
extern struct YourStruct *yourstruct_instance;

在其中一个标头中应该完成此工作。

从c库导出结构的实例。让C++库包含一个来自C库的头文件。

在C库中的.h文件中:

#ifdef __cplusplus
extern "C" {
#endif
__declspec(dllexport) struct MyStruct
{
    // members
}
extern __declspec(dllexport) struct MyStruct myInstance;
#ifdef __cplusplus
}
#endif

在c库中的.c文件中:

__declspec(dllexport) struct MyStruct myInstance;

然后,您的c和c++代码可以操作myInstance

请参阅本文了解更多信息。此外,请尝试创建一个新的C++dll项目,并选中"导出符号"框。这将创建一个带有导出类和该类实例的c++dll。在c中对导出的结构执行同样的操作非常相似。