On 4/24/13 1:57 PM, Somostetoi Kilato wrote:
Hi Richard,

Thank you for your comment. You are totally right, but this was only a small example what I made after a long learning period :-)
But I would like to know, if I have for example a small C++ library, within the classes are in a custom name space, how should I write my C wrapper to use those classes?

Thank you and all the best,
Kilato Somostetoi


C code can not directly reference a class/struct that uses any feature not in C, this includes things like namespaces, access specifiers, member functions, etc. You may be able to get some of these to compile with #ifdef __cplusplus conditionals.

If the C code only needs to deal with pointers to the class, then you can either use the void* pointers as you example (and the wrapper classes then need to use void* pointers too), or I believe you can use a pointer to an incomplete struct.

Thus the C code could see things like

struct Apple;
 
extern Apple* pick_an_apple();
...

Apple* the_apple = pick_an_apple();


while the C++ code could be someing like:

namespace custom {

  class Apple {
 ...
 };
};

extern "C" custom::Apple* pick_an_apple() {
}

This should work as C code does NOT use the actual name of a struct to determine if structs are compatible, and all struct pointers are stored the same way, so you can cast one struct pointer to another type of struct pointer and back and be allowed to access the object.

It may be easiest to write the code with something like:

#ifdef __cplusplus
namespace custom {
  call Apple {

  };
};
typedef custom::Apple *pApple;

#else
struct Apple;
typedef Apple *pApple;
#endif

now pApple will be a pointer to a incomplete struct in C, suitable for passing around addresses, while in C++ code, will be a pointer to the class in its namespace. Of course, any function that the C code calls must be declared extern "C".
-- 
Richard Damon