简体   繁体   English

从C代码调用C ++方法

[英]calling C++ method from C code

I've read the following article here that explain how to call c++ based functions from pure C code. 我在这里阅读了以下文章,解释了如何从纯C代码调用基于c ++的函数。

The method is best explained with the following example : 下面的示例可以最好地说明该方法:

// C++ code:
class C {
    // ...
    virtual double f(int);
};
extern "C" double call_C_f(C* p, int i) // wrapper function
{
    return p->f(i);
}

/* C code: */
double call_C_f(struct C* p, int i);
void ccc(struct C* p, int i)
{
    double d = call_C_f(p,i);
    /* ... */
}

However, I fail to understand if where do i define an instance that is pointed by 'p'. 但是,我不明白是否在哪里定义由“ p”指向的实例。 notice that in the C code, it is delivered as pointer to opaque struct, and in the C++ code it's assumed to be pointer to valid instance of class C , but i didn't see where this pointer is being initialized. 请注意,在C代码中,它作为指向不透明结构的指针提供,在C ++代码中,它被假定为指向class C有效实例的指针,但是我没有看到此指针的初始化位置。

ps Of course that each code block that relate to different language is compiled with an appropriate compiler, and different object file is created. ps当然,与不同语言相关的每个代码块都使用适当的编译器进行编译,并创建了不同的目标文件。

You need similar wrapper methods to create and destroy the C++ object. 您需要类似的包装器方法来创建和销毁C ++对象。

C++ code: C ++代码:

extern "C" C * create_c()
{
    return new C;
}

extern "C" void destroy_c(C *p)
{
    delete p;
}

C code: C代码:

// forward declarations (better to put those in a header file)
struct C;
struct C * create_c();
double call_C_f(struct C* p, int i);
void destroy_c(struct C *p);

struct C * p = create_c();
double result = call_C_f(p, i);
destroy_c(p);
p = NULL;

In the case of your example, p is an object of your class C . 在您的示例中, p是类C的对象。 You would have to create it in C++ code, and than pass it to C. 您必须使用C ++代码创建它,然后将其传递给C。

You should also declare the pointers to your C++ class as void * in C. The type is unknown, and struct C implies it's a known struct, which is wrong. 您还应该在C中将指向C ++类的指针声明为void * 。类型是未知的,并且struct C暗示它是已知的结构,这是错误的。

Example: 例:

extern "C" {
struct C;
struct C *create_c(void)
{
     return new C;
}

void destroy_c(struct C *ptr)
{
    delete ((C*)ptr);
}
}

You'd create it in C++, most probably with new C() . 您将使用C ++创建它,最有可能使用new C()创建它。 There is no way of portably creating it in C, so in case the C code must be able to construct new instances, you'd have to write an extern "C" C* construct_C(); 没有办法在C中移植它,因此,如果C代码必须能够构造新的实例,则必须编写一个extern "C" C* construct_C(); factory function for it; 它的工厂功能; likewise for a destructor. 同样对于析构函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM