c interface with c++ implementation

Z

zade

I want to create a library with c interface but with c++
implementation. But I don't know if there exist some potential
problems.
Any advice? thanks!
 
C

comp.lang.c++.moderated

I want to create a library with c interface but with c++
implementation. But I don't know if there exist some potential
problems.
Any advice? thanks!

There's no potential problem, As far as I did in my previous project

Here's a small example

//A.h
class A {
public:
A(char);
int Func(int);
};

// c_interface.h
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus

typedef void* A_HANDLE;

A_HANDLE create_A(char c);

void destroy_A(A_HANDLE h);

int c_func(A_HANDLE, int);
// other C functions ...
#ifdef __cplusplus
}
#endif // __cplusplus

// a.cpp
#include "a.h"
#include "c_interface.h"

A::A(char c) {
}

int A::Func(int i) {

}

A_HANDLE create_A(char c) {
new A(c);
}

void destroy_A(A_HANDLE h) {
delete static_cast<A*>(h);
}

int c_func(A_HANDLE h, int i) {
A* pA = static_cast<A*>(h);
return pA->Func(i);
}

//test.c
#include "c_interface.h"
A_HANDLE hA = create_A('a');

int ret = c_func(10);

destroy_A(hA);
 
R

Roland Pibinger

There's no potential problem, As far as I did in my previous project

There may be problems, e.g. with the initialization of global
variables.
Here's a small example

//A.h
class A {
public:
A(char);
int Func(int);
};

// c_interface.h
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus

typedef void* A_HANDLE;

No need to use a void* here.
 
C

comp.lang.c++.moderated

There may be problems, e.g. with the initialization of global
variables.

just define the global variables in corresponding the cxx files, and
define pointer to the variables which can be accessed in c files, also
provide getter/setter functions if needed.
Anyway, the implementation is tedious.
No need to use a void* here.

type define produce memorial type names
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top