In summary, I have written a C++ library and am now making a C wrapper to let C programmer use my lib.
I am able to get it to work by using raw pointers. Here’s what I do.
// some_class.hpp
namespace AAA {
class SomeClass{
int some_func(int a, int b);
};
}
// c_wrapper.h
# include <stddef.h>
typedef void* c_wrapper_some_class_t;
extern size_t const SOME_CLASS_SIZE;
c_wrapper_some_class_t* some_class_construct(void *mem, size_t size);
int some_class_some_func(c_wrapper_some_class_t *obj, int a, int b);
// c_wrapper.cpp
#include <new>
#include <stddef.h>
#include "c_wrapper.h"
extern "C"
{
size_t const SOME_CLASS_SIZE = sizeof(AAA::SomeClas);
c_wrapper_some_class_t *some_class_construct(void *mem, size_t size)
{
if (size< SOME_CLASS_SIZE || mem == nullptr )
{
return nullptr;
}
return new (mem) AAA::SomeClass; // Placement new
}
int some_class_some_func(c_wrapper_some_class_t *obj, int a, int b){
return reinterpret_cast<AAA::SomeClass*>(obj)->some_func(a,b);
}
}
With this, someone can do something like
// main.c
#include "c_wrapper.h"
void * mem = malloc(SOME_CLASS_SIZE);
c_wrapper_some_class_t* obj = some_class_construct(mem);
int c = some_class_some_func(obj, 1,2);
Yay! It works.
Now, can I get the size of SomeClass at compile time? I can make it work with dynamic allocation, but cannot do it cleanly with static allocation. It would work if I ask the user to “guess” the size of the class and they provide something that happens to be big enough.
The only way I can see it could work cleanly-ish would be that, after building the c_wrapper.o, I use objdump to extract the size and the write a custom made .h with the value written, like using CMake template.
Not that my lib is for embedded platform and is meant to be portable.