在C和C++库之间共享变量的困境
Sharing a variable between C and C++ libraries dilemma
我有一个简单的问题。我有两个库,一个用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中对导出的结构执行同样的操作非常相似。
相关文章:
- C++子类共享变量?
- 子目录之间的 CMAKE 共享变量
- 如何在不同的CMakeList.txt之间共享变量?
- OpenMP 任务看不到共享变量的更改
- OpenMP:当我按线程 ID 访问共享变量时,我是否需要一个关键部分
- 多个 OpenMP 线程读取(而不是写入)共享变量的性能成本?
- 在 pthread 中使用共享变量
- 提升线程问题,当一个线程与另一个线程没有相同的副本时如何共享变量?
- C :与多个文件共享变量
- 使用共享变量进行线程处理
- 是否要确保一个线程修改的任何数据类型的共享变量对其他线程可见
- 在派生类之间复制共享变量(浅副本就足够了)
- 为什么跨线程更改共享变量的代码显然没有受到竞争条件的影响
- 从多个线程C 更改共享变量
- 在不同类的对象之间共享变量 (C++)
- 管理多线程应用程序中的共享变量
- C 类共享变量
- 增强多线程和共享变量
- 共享变量和局部变量C++
- 在C和C++库之间共享变量的困境