如何使用C ++对象在C? [英] How to use c++ objects in c?

查看:155
本文介绍了如何使用C ++对象在C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个项目去codeR和DEC在我的视觉工作室。其中有C code等使用STL respectively.How有C ++ code做我实例化德code项目中我的C code中的C ++类?

I have 2 projects decoder and dec in my visual studio. One has C code and other has C++ code using stl respectively.How do I instantiate the c++ classes in my c code inside decode project?

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

什么我需要为此做什么?

What do I need to do for this?

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

How do I access files from another project?

我如何利用现有的C ++ code的C文件?

How do I make use of existing c++ code in C files?

-------- ----------编辑
我有这样一个类

--------edit---------- I have a class like this

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只允许结构如何将其映射到一个结构?

How do I use the above class in c++? If C only allows structs how do I map it to a struct?

推荐答案

给C ++的模块C接口:

Give the C++ module a C interface:

magic.hpp:

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

magic.cpp:(实施魔术

magic_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

magic_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程序的#includemagic_interface.h,并使用code:

Now a C program can #include "magic_interface.h" and use the code:

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

(你甚至可能要定义 MHandle 无效* 并添加蒙上到处以免声明结构魔术的C头都没有。)

(You might even want to define MHandle as void * and add casts everywhere so as to avoid declaring struct Magic in the C header at all.)

这篇关于如何使用C ++对象在C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆