我的 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);
};
magic.cpp:(实现Magic
。)
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 程序可以#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/