c++ - 如何在 C 中使用 C++ 对象?

标签 c++ c

我的 Visual Studio 中有 2 个项目 decoder 和 dec。一个有 C 代码,另一个有分别使用 STL 的 C++ 代码。如何在我的解码项目中的 C 代码中实例化 C++ 类?

for e.g.
//instantiating object
reprVectorsTree *r1 = new reprVectorsTree(reprVectors1,8);
//using one of its function
r1->decode(code);

我需要为此做什么?

如何从另一个项目访问文件?

如何在 C 文件中使用现有的 C++ 代码?

--------编辑---------- 我有这样的类(class)

class Node//possible point in our input space
{
public:
    std::vector<float> valuesInDim;//values in dimensions
    std::vector<bool> code;
    Node(std::vector<float>value);
    Node::Node(float x, float y);
Node::Node(std::vector<float> value,std::vector<bool> binary);


};

如何在 C++ 中使用上述类? 如果 C 只允许结构,我该如何将其映射到结构?

最佳答案

给C++模块一个C接口(interface):

魔法.hpp:

struct Magic
{
    Magic(char const *, int);
    double work(int, int);
};

ma​​gic.cpp:(实现Magic。)

ma​​gic_interface.h:

struct Magic;

#ifdef __cplusplus
extern "C" {
#endif

typedef Magic * MHandle;
MHandle create_magic(char const *, int);
void    free_magic(MHandle);
double  work_magic(MHandle, int, int);

#ifdef __cplusplus
}
#endif

ma​​gic_interface.cpp:

#include "magic_interface.h"
#include "magic.hpp"

extern "C"
{
    MHandle create_magic(char const * s, int n) { return new Magic(s, n); }
    void    free_magic(MHandle p) { delete p; }
    double  work_magic(MHandle p, int a, int b) { return p->work(a, b); }
}

现在 C 程序可以#include "magic_interface.h" 并使用代码:

MHandle h = create_magic("Hello", 5);
double d = work_magic(h, 17, 29);
free_magic(h);

(您甚至可能想将 MHandle 定义为 void * 并在各处添加强制转换以避免在 C header 中声明 struct Magic完全没有。)

关于c++ - 如何在 C 中使用 C++ 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11971063/

相关文章:

c++ - 在 PhysX 中编辑一个 Actor 的重力

C++:用 const 成员替换类数组的元素

c++ - boost::shared_ptr 销毁回调

c++ - 将路径传递给 CreateProcessA

c# - 从 STL 容器中弹出时,为什么 c# 可以返回对象而 c++ 不能?

c - 字符串作为函数参数并从 C 中的函数返回字符串

编译 C 以允许缓冲区溢出

c - Linux 的动态链接器 : how to call a function from the main process from an . 所以对象?

c - 尝试接受字符并删除空格

c++ - 将 shared_ptr 传递给 OpenGL?