I have 2 projects decoder and dec in my visual studio. One has C code and other has C++ code using stl respectively.How do I instantiate the c++ classes in my c code inside decode project?
for e.g.
//instantiating object
reprVectorsTree *r1 = new reprVectorsTree(reprVectors1,8);
//using one of its function
r1->decode(code);
What do I need to do for this?
How do I access files from another project?
How do I make use of existing c++ code in C files?
--------edit----------
I have a class like this
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);
};
How do I use the above class in c++?
If C only allows structs how do I map it to a struct?
Give the C++ module a C interface:
magic.hpp:
struct Magic
{
Magic(char const *, int);
double work(int, int);
};
magic.cpp: (Implement 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); }
}
Now a C program can #include "magic_interface.h" and use the code:
MHandle h = create_magic("Hello", 5);
double d = work_magic(h, 17, 29);
free_magic(h);
(You might even want to define MHandle as void * and add casts everywhere so as to avoid declaring struct Magic in the C header at all.)
In simple terms, you just do these:
Write an interface function to convert all the class functions (constructor, destructor, member functions) as pure functions, and encapsulate them as extern "C"{ }
Convert the pointer to the class as pointer to void, and carefully use type-cast wherever you define the "pure functions"
Call the pure functions in the C-code.
For example here is my simple Rectangle class:
/*** Rectangle.h ***/
class Rectangle{
private:
double length;
double breadth;
public:
Rectangle(double iLength, double iBreadth);
~Rectangle();
double getLength();
double getBreadth();
};
/*** Rectangle.cpp ***/
#include "Rectangle.h"
#include <iostream>
extern "C" {
Rectangle::Rectangle(double l, double b) {
this->length = l;
this->breadth = b;
}
Rectangle::~Rectangle() {
std::cout << "Deleting object of this class Rectangle" << std::endl;
}
double Rectangle::getLength() {
return this->length;
}
double Rectangle::getBreadth() {
return this->breadth;
}
}
Now here is my interface to convert the class functions to pure functions. Notice how the pointer to the class is handled!
/*** RectangleInterface.h ***/
#ifdef __cplusplus
extern "C" {
#endif
typedef void * RHandle;
RHandle create_Rectangle(double l, double b);
void free_Rectangle(RHandle);
double getLength(RHandle);
double getBreadth(RHandle);
#ifdef __cplusplus
}
#endif
/*** RectangleInterface.cpp ***/
#include "RectangleInterface.h"
#include "Rectangle.h"
extern "C"
{
RHandle create_Rectangle(double l, double b){
return (Rectangle*) new Rectangle(l, b);
};
void free_Rectangle(RHandle p){
delete (Rectangle*) p;
}
double getLength(RHandle p){
return ((Rectangle*) p)->getLength();
}
double getBreadth(RHandle p){
return ((Rectangle*)p)->getBreadth();
}
}
Now I can use these interface functions in my ".c" file as shown below. I just have to include the RectangleInterface.h function here, and the rest is taken care by its functions.
/*** Main function call ***/
#include <stdio.h>
#include "RectangleInterface.h"
int main()
{
printf("Hello World!!\n");
RHandle myRec = create_Rectangle(4, 3);
printf("The length of the rectangle is %f\n", getLength(myRec));
printf("The area of the rectangle is %f\n", (getLength(myRec)*getBreadth(myRec)));
free_Rectangle(myRec);
return 0;
}
Make wrapper for instantiating C++ objects using C++ exported functions.And then call these functions from C code to generate objects.
Since one is function oriented and other is object oriented, you can use a few ideas in your wrapper:-
In order to copy class member, pass an equivalent prespecified struct from C code to corresponding C++ function in order to fetch the data.
Try using function pointers, as it will cut the cost, but be careful they can be exploited as well.
A few other ways.
you would need to write a wrapper in C.
something like this:
in class.h:
struct A{
void f();
}
in class.cpp:
void A::f(){
}
the wrapper.cpp:
#include "wrapper.h"
void fWrapper(struct A *a){a->f();};
struct A *createA(){
A *tmp=new A();
return tmp;
}
void deleteA(struct A *a){
delete a;
}
the wrapper.h for C:
struct A;
void fWrapper(struct A *a);
A *createA();
the C program:
#include "wrapper.h"
int main(){
A *a;
a=createA();
fWrapper(a);
deleteA(a);
}
Related
Let's say we have a C++ library with a class like this:
class TheClass {
public:
TheClass() { ... }
void magic() { ... }
private:
int x;
}
Typical usage of this class would include stack allocation:
TheClass object;
object.magic();
We need to create a C wrapper for this class. The most common approach looks like this:
struct TheClassH;
extern "C" struct TheClassH* create_the_class() {
return reinterpret_cast<struct TheClassH*>(new TheClass());
}
extern "C" void the_class_magic(struct TheClassH* self) {
reinterpret_cast<TheClass*>(self)->magic();
}
However, it requires heap allocation, which is clearly not desired for such a small class.
I'm searching for an approach to allow stack allocation of this class from C code. Here is what I can think of:
struct TheClassW {
char space[SIZEOF_THECLASS];
}
void create_the_class(struct TheClassW* self) {
TheClass* cpp_self = reinterpret_cast<TheClass*>(self);
new(cpp_self) TheClass();
}
void the_class_magic(struct TheClassW* self) {
TheClass* cpp_self = reinterpret_cast<TheClass*>(self);
cpp_self->magic();
}
It's hard to put real content of the class in the struct's fields. We can't just include C++ header because C wouldn't understand it, so it would require us to write compatible C headers. And this is not always possible. I think C libraries don't really need to care about content of structs.
Usage of this wrapper would look like this:
TheClassW object;
create_the_class(&object);
the_class_magic(&object);
Questions:
Does this approach have any dangers or drawbacks?
Is there an alternative approach?
Are there any existing wrappers that use this approach?
You can use placement new in combination of alloca to create an object on the stack. For Windows there is _malloca. The importance here is that alloca, and malloca align memory for you accordingly and wrapping the sizeof operator exposes the size of your class portably. Be aware though that in C code nothing happens when your variable goes out of scope. Especially not the destruction of your object.
main.c
#include "the_class.h"
#include <alloca.h>
int main() {
void *me = alloca(sizeof_the_class());
create_the_class(me, 20);
if (me == NULL) {
return -1;
}
// be aware return early is dangerous do
the_class_magic(me);
int error = 0;
if (error) {
goto fail;
}
fail:
destroy_the_class(me);
}
the_class.h
#ifndef THE_CLASS_H
#define THE_CLASS_H
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
class TheClass {
public:
TheClass(int me) : me_(me) {}
void magic();
int me_;
};
extern "C" {
#endif
size_t sizeof_the_class();
void *create_the_class(void* self, int arg);
void the_class_magic(void* self);
void destroy_the_class(void* self);
#ifdef __cplusplus
}
#endif //__cplusplus
#endif // THE_CLASS_H
the_class.cc
#include "the_class.h"
#include <iostream>
#include <new>
void TheClass::magic() {
std::cout << me_ << std::endl;
}
extern "C" {
size_t sizeof_the_class() {
return sizeof(TheClass);
}
void* create_the_class(void* self, int arg) {
TheClass* ptr = new(self) TheClass(arg);
return ptr;
}
void the_class_magic(void* self) {
TheClass *tc = reinterpret_cast<TheClass *>(self);
tc->magic();
}
void destroy_the_class(void* self) {
TheClass *tc = reinterpret_cast<TheClass *>(self);
tc->~TheClass();
}
}
edit:
you can create a wrapper macro to avoid separation of creation and initialization. you can't use do { } while(0) style macros because it will limit the scope of the variable. There is other ways around this but this is highly dependent on how you deal with errors in the code base. A proof of concept is below:
#define CREATE_THE_CLASS(NAME, VAL, ERR) \
void *NAME = alloca(sizeof_the_class()); \
if (NAME == NULL) goto ERR; \
// example usage:
CREATE_THE_CLASS(me, 20, fail);
This expands in gcc to:
void *me = __builtin_alloca (sizeof_the_class()); if (me == __null) goto fail; create_the_class(me, (20));;
There are alignment dangers. But maybe not on your platform. Fixing this may require platform specific code, or C/C++ interop that is not standardized.
Design wise, have two types. In C, it is struct TheClass;. In C++, struct TheClass has a body.
Make a struct TheClassBuff{char buff[SIZEOF_THECLASS];};
TheClass* create_the_class(struct TheClassBuff* self) {
return new(self) TheClass();
}
void the_class_magic(struct TheClass* self) {
self->magic();
}
void the_class_destroy(struct TheClass* self) {
self->~TheClass();
}
C is supposed to make the buff, then create a handle from it and interact using it. Now usually that isn't required as reinterpreting pointer to theclassbuff will work, but I think that is undefined behaviour technically.
Here is another approach, which may or may not be acceptable, depending on the application specifics. Here we basically hide the existence of TheClass instance from C code and encapsulate every usage scenario of TheClass in a wrapper function. This will become unmanageable if the number of such scenarios is too large, but otherwise may be an option.
The C wrapper:
extern "C" void do_magic()
{
TheClass object;
object.magic();
}
The wrapper is trivially called from C.
Update 2/17/2016:
Since you want a solution with a stateful TheClass object, you can follow the basic idea of your original approach, which was further improved in another answer. Here is yet another spin on that approach, where the size of the memory placeholder, provided by the C code, is checked to ensure it is sufficiently large to hold an instance of TheClass.
I would say that the value of having a stack-allocated TheClass instance is questionable here, and it is a judgement call depending on the application specifics, e.g. performance. You still have to call the de-allocation function, which in turn calls the destructor, manually, since it is possible that TheClass allocates resources that have to be released.
However, if having a stack-allocated TheClass is important, here is another sketch.
The C++ code to be wrapped, along with the wrapper:
#include <new>
#include <cstring>
#include <cstdio>
using namespace std;
class TheClass {
public:
TheClass(int i) : x(i) { }
// cout doesn't work, had to use puts()
~TheClass() { puts("Deleting TheClass!"); }
int magic( const char * s, int i ) { return 123 * x + strlen(s) + i; }
private:
int x;
};
extern "C" TheClass * create_the_class( TheClass * self, size_t len )
{
// Ensure the memory buffer is large enough.
if (len < sizeof(TheClass)) return NULL;
return new(self) TheClass( 3 );
}
extern "C" int do_magic( TheClass * self, int l )
{
return self->magic( "abc", l );
}
extern "C" void delete_the_class( TheClass * self )
{
self->~TheClass(); // 'delete self;' won't work here
}
The C code:
#include <stdio.h>
#define THE_CLASS_SIZE 10
/*
TheClass here is a different type than TheClass in the C++ code,
so it can be called anything else.
*/
typedef struct TheClass { char buf[THE_CLASS_SIZE]; } TheClass;
int do_magic(TheClass *, int);
TheClass * create_the_class(TheClass *, size_t);
void delete_the_class(TheClass * );
int main()
{
TheClass mem; /* Just a placeholder in memory for the C++ TheClass. */
TheClass * c = create_the_class( &mem, sizeof(TheClass) );
if (!c) /* Need to make sure the placeholder is large enough. */
{
puts("Failed to create TheClass, exiting.");
return 1;
}
printf("The magic result is %d\n", do_magic( c, 232 ));
delete_the_class( c );
return 0;
}
This is just a contrived example for illustration purposes. Hopefully it is helpful. There may be subtle problems with this approach, so testing on your specific platform is highly important.
A few additional notes:
THE_CLASS_SIZE in the C code is just the size of a memory buffer in which
a C++'s TheClass instance is to be allocated; we are fine as long as
the size of the buffer is sufficient to hold a C++'s TheClass
Because TheClass in C is just a memory placeholder, we might just as
well use a void *, possibly typedef'd, as the parameter type in the
wrapper functions instead of TheClass. We would reinterpret_cast
it in the wrapper code, which would actually make the code clearer:
pointers to C's TheClass are essentially reinterpreted as C++'s TheClass anyway.
There is nothing to prevent C code from passing a TheClass* to the
wrapper functions that doesn't actually point to a C++'s TheClass
instance. One way to solve this is to store pointers to properly
initialized C++ TheClass instances in some sort of a data structure
in the C++ code and return to the C code handles that can be used to
look up these instances.
To use couts in the C++ wrapper we need to link with
the C++ standard lib when building an executable. For example, if
the C code is compiled into main.o and C++ into lib.o, then on
Linux or Mac we'd do gcc -o junk main.o lib.o -lstdc++.
It worth to keep each piece of knowledge in a single place, so I would suggest to make a class code "partially readable" for C. One may employ rather simple set of macro definitions to enable it to be done in short and standard words. Also, a macro may be used to invoke constructor and destructor at the beginning and the end of stack-allocated object's life.
Say, we include the following universal file first into both C and C++ code:
#include <stddef.h>
#include <alloca.h>
#define METHOD_EXPORT(c,n) (*c##_##n)
#define CTOR_EXPORT(c) void (c##_construct)(c* thisPtr)
#define DTOR_EXPORT(c) void (c##_destruct)(c* thisPtr)
#ifdef __cplusplus
#define CL_STRUCT_EXPORT(c)
#define CL_METHOD_EXPORT(c,n) n
#define CL_CTOR_EXPORT(c) c()
#define CL_DTOR_EXPORT(c) ~c()
#define OPT_THIS
#else
#define CL_METHOD_EXPORT METHOD_EXPORT
#define CL_CTOR_EXPORT CTOR_EXPORT
#define CL_DTOR_EXPORT DTOR_EXPORT
#define OPT_THIS void* thisPtr,
#define CL_STRUCT_EXPORT(c) typedef struct c c;\
size_t c##_sizeof();
#endif
/* To be put into a C++ implementation coce */
#define EXPORT_SIZEOF_IMPL(c) extern "C" size_t c##_sizeof() {return sizeof(c);}
#define CTOR_ALIAS_IMPL(c) extern "C" CTOR_EXPORT(c) {new(thisPtr) c();}
#define DTOR_ALIAS_IMPL(c) extern "C" DTOR_EXPORT(c) {thisPtr->~c();}
#define METHOD_ALIAS_IMPL(c,n,res_type,args) \
res_type METHOD_EXPORT(c,n) args = \
call_method(&c::n)
#ifdef __cplusplus
template<class T, class M, M m, typename R, typename... A> R call_method(
T* currPtr, A... args)
{
return (currPtr->*m)(args...);
}
#endif
#define OBJECT_SCOPE(t, v, body) {t* v = alloca(t##_sizeof()); t##_construct(v); body; t##_destruct(v);}
Now we can declare our class (the header is useful both in C and C++, too)
/* A class declaration example */
#ifdef __cplusplus
class myClass {
private:
int y;
public:
#endif
/* Also visible in C */
CL_STRUCT_EXPORT(myClass)
void CL_METHOD_EXPORT(myClass,magic) (OPT_THIS int c);
CL_CTOR_EXPORT(myClass);
CL_DTOR_EXPORT(myClass);
/* End of also visible in C */
#ifdef __cplusplus
};
#endif
Here is the class implementation in C++:
myClass::myClass() {std::cout << "myClass constructed" << std::endl;}
CTOR_ALIAS_IMPL(myClass);
myClass::~myClass() {std::cout << "myClass destructed" << std::endl;}
DTOR_ALIAS_IMPL(myClass);
void myClass::magic(int n) {std::cout << "myClass::magic called with " << n << std::endl;}
typedef void (myClass::* myClass_magic_t) (int);
void (*myClass_magic) (myClass* ptr, int i) =
call_method<myClass,myClass_magic_t,&myClass::magic,void,int>;
and this is a using C code example
main () {
OBJECT_SCOPE(myClass, v, {
myClass_magic(v,178);
})
}
It's short and working! (here's the output)
myClass constructed
myClass::magic called with 178
myClass destructed
Note that a variadic template is used and this requires c++11. However, if you don't want to use it, a number of fixed-size templates ay be used instead.
Here's how one might do it safely and portably.
// C++ code
extern "C" {
typedef void callback(void* obj, void* cdata);
void withObject(callback* cb, void* data) {
TheClass theObject;
cb(&theObject, data);
}
}
// C code:
struct work { ... };
void myCb (void* object, void* data) {
struct work* work = data;
// do whatever
}
// elsewhere
struct work work;
// initialize work
withObject(myCb, &work);
What I did in alike situation is something like:
(I omit static_cast, extern "C")
class.h:
class TheClass {
public:
TheClass() { ... }
void magic() { ... }
private:
int x;
}
class.cpp
<actual implementation>
class_c_wrapper.h
void* create_class_instance(){
TheClass instance = new TheClass();
}
void delete_class_instance(void* instance){
delete (TheClass*)instance;
}
void magic(void* instance){
((TheClass*)instance).magic();
}
Now, you stated that you need stack allocation. For this I can suggest rarely used option of new: placement new. So you'd pass additional parameter in create_class_instance() that is pointing to an allocated buffer enough to store class instance, but on stack.
This is how I would solve the issue (basic idea is to let interprete C and C++ the same memory and names differently):
TheClass.h:
#ifndef THECLASS_H_
#define THECLASS_H_
#include <stddef.h>
#define SIZEOF_THE_CLASS 4
#ifdef __cplusplus
class TheClass
{
public:
TheClass();
~TheClass();
void magic();
private:
friend void createTheClass(TheClass* self);
void* operator new(size_t, TheClass*) throw ();
int x;
};
#else
typedef struct TheClass {char _[SIZEOF_THE_CLASS];} TheClass;
void create_the_class(struct TheClass* self);
void the_class_magic(struct TheClass* self);
void destroy_the_class(struct TheClass* self);
#endif
#endif /* THECLASS_H_ */
TheClass.cpp:
TheClass::TheClass()
: x(0)
{
}
void* TheClass::operator new(size_t, TheClass* self) throw ()
{
return self;
}
TheClass::~TheClass()
{
}
void TheClass::magic()
{
}
template < bool > struct CompileTimeCheck;
template < > struct CompileTimeCheck < true >
{
typedef bool Result;
};
typedef CompileTimeCheck< SIZEOF_THE_CLASS == sizeof(TheClass) >::Result SizeCheck;
// or use static_assert, if available!
inline void createTheClass(TheClass* self)
{
new (self) TheClass();
}
extern "C"
{
void create_the_class(TheClass* self)
{
createTheClass(self);
}
void the_class_magic(TheClass* self)
{
self->magic();
}
void destroy_the_class(TheClass* self)
{
self->~TheClass();
}
}
The createTheClass function is for friendship only - I wanted to avoid the C wrapper functions to be publicly visible within C++. I caught up the array variant of the TO, because I consider this better readable than the alloca approach. Tested with:
main.c:
#include "TheClass.h"
int main(int argc, char*argv[])
{
struct TheClass c;
create_the_class(&c);
the_class_magic(&c);
destroy_the_class(&c);
}
I tried to compile and link the second example (see below), in the second FAQ in this link in isocpp.org.
Naturally, this works only for non-member functions. If you want to
call member functions (incl. virtual functions) from C, you need to
provide a simple wrapper. For 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);
}
Now C::f() can be used like this:
/* 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);
/* ... */
}
After several trials, I succeeded executing the example in VS2015. But I'm still not convinced about the declaration extern "C" struct C *p = &c; that I had to use in other.cpp (I simply couldn't make the code to work with anything different than this). Note that the C++ compiler emits the following warning for the alluded declaration:
warning C4099: 'C': type name first seen using 'class' now seen using
'struct'
main.c was compiled with the C compiler and other.cpp with the C++ compiler.
main.c
/* C code: */
#include <stdio.h>
extern struct C *p;
double call_C_f(struct C* p, int i);
void ccc(struct C* p, int i)
{
double d = call_C_f(p, i);
printf("%f", d);
}
int main()
{
ccc(p, 1);
}
other.cpp
// C++ code:
class C {
public:
virtual double f(int i) { return i; };
} c;
extern "C" struct C *p = &c; // This is the declaration that I'm concerned about
// Is it correct?
extern "C" double call_C_f(C* p, int i) // wrapper function
{
return p->f(i);
}
The line extern "C" struct C *p = &c is IMHO more confusing than really useful. In the same C++ compilation unit you first declare C to be a class, then a struct. As already said in comment with refs in that other question, declaring a class once with struct and once with class may lead to mangling issues in C++ code.
And it is useless, because as C is not a POD struct (it contains method and even a virtual one) it cannot be used from C as a struct, and in fact you only use a pointer to C from c code as an opaque pointer.
So the line should be written:
extern "C" class C *p = &c;
declaring to the compiler that you are defining a pointer to class C with extern linkage named p, pointing to c. Perfectly defined from C++ perspective.
Next from C point of view, you declare the extern pointer p, pointing to an undefined struct C. C will only allow you to use it almost a void pointer, meaning you can affect it and pass it to function, but p->xxx would cause an error because struct C is not fully declared in that compilation unit.
In fact the following code does exactly the same as yours without any warning:
main.c
/* C code: */
#include <stdio.h>
extern struct D *p;
double call_C_f(struct D* p, int i);
void ccc(struct D* p, int i)
{
double d = call_C_f(p, i);
printf("%f", d);
}
int main()
{
ccc(p, 1);
return 0; /* never return random value to environment */
}
other.cpp
// C++ code:
class C {
public:
virtual double f(int i) { return i; };
} c;
extern "C" C *p = &c;
extern "C" double call_C_f(C* p, int i) // wrapper function
{
return p->f(i);
}
The usage of struct D is not a typo. Of course I should have used struct C to avoid confusion for the reader, but it is not a problem for the compiler not for the linker: p in main.c is just a pointer to an opaque not fully declared struct. That's the reason why, it is common to declare such opaque pointers as void *.
I new in C++ and I have difficulty to understand how to get my function with inheritance.
I have a Class that is link to another with inheritance, everything work except:
I cannot reach my superclass function.
Here's my class header : Point.h (I don't include the .cpp):
#ifndef Point_H
#define Point_H
#include <iostream>
class Point{
public:
Point();
void set_values (int , int);
void set_values (int , int , int );
void affichervaleurs();
int getX() const { return x; }
int getY() const { return y; }
private:
int x ;
int y ;
int z ;
};
#endif
Now My other class that try to access the function getX from Point.h :
The header : Carre.h
#ifndef Carre_H
#define Carre_H
#include "Point.h"
class Carre : public Point{
public:
Carre();
//Carre(int a , int b);
//Carre(int a, int b):Point(a,b) {};
//Carre(int a, int b, int c):Point(a, b, c) {};
//const Point &pp;
int Aire (){
};
void affichercar(){
};
};
#endif
Carre.cpp
#include <iostream>
using namespace std;
#include "Carre.h"
#include "Point.h"
Carre::Carre():Point(){
};
//Carre::Carre(int a, int b);
//const &pp;
int Aire (){
return (getX() * getY());
};
void affichercar(){
//cout << "Coordonnees X:" << x << endl;
};
It says that my GetX() is undeclared in my Carre.cpp .
Like I said I'm new in C++
Does someone know what I'm missing to make that code work. ?
Your definition is missing the class scope, which makes it a free function instead of a member.
It should be
int Carre::Aire (){
return getX() * getY();
};
In the .cpp file for Carre, the functions Aire and affichercar are global. Presumably you intended:
int Carre::Aire(){
return (getX() * getY());
};
For example.
Declaring function outside class body requires a class specifier:
int Carre::Aire () {
return (getX() * getY());
};
void Carre::affichercar() {
//...
}
Otherwise
int Aire () {
return (getX() * getY());
};
is just another function in global namespace that can exists simutaneously to Carre::Aire().
This is because you are not implementing the Aire function as being part of the Carre class.
Try changing
int Aire (){
to
int Carre::Aire (){
Also, you already have an implementation of the Aire method in the header file. You should either implement the function inline in the header file, or in the .cpp file, but not both. This also applies to your affichercar method.
I have successfully used MacFUSE in the C programming language on OS X 10.6.8 and it works great.
At some point I need to start making functions calls to a C++ static library (libSomething.a). From this question people are saying the only way this is possible is modify the c++ source code to make it callable from C (i.e. prepend extern "C" before function name and return type). Unfortunately, I do not have access to the source code, just a static C++ library *.a file.
Is there some way I can convert MacFUSE into a C++ or Objective-C program to allow for invoking C++ functions inside a static library?
I would appreciate the C/C++/Objective-C experts in the community to weigh in on this.
I'm using Xcode 4.3
You could provide a wrapper, exposing the C++ class as a C-API:
Something.h:
class Something {
protected:
int x;
public:
Something() { x = 0; }
void setX(int newX) { x = newX; }
int getX() const { return x; }
};
wrapper.h:
#pragma once
typedef void *SOMETHING;
#ifdef __cplusplus
extern "C" {
#endif
SOMETHING createSomething();
void destroySomething(SOMETHING something);
void setSomethingX(SOMETHING something, int x);
int getSomethingX(SOMETHING something);
#ifdef __cplusplus
} // extern "C"
#endif
wrapper.cpp:
#include <Something.h>
#include "wrapper.h"
SOMETHING createSomething() {
return static_cast<SOMETHING>(new Something());
}
void destroySomething(SOMETHING something) {
delete static_cast<Something *>(something);
}
void setSomethingX(SOMETHING something, int x) {
static_cast<Something *>(something)->setX(x);
}
int getSomethingX(SOMETHING something) {
return static_cast<Something *>(something)->getX();
}
I'm getting a segfault on line 15 of my .cpp file. I'm not sure why. Various code snippets:
explosionhandler.h:
class explosionhandler {
public:
struct explosion {
...
};
vector<struct explosion> explosions;
struct explosion_type {
...
};
vector<struct explosion_type> type;
int num_types;
explosionhandler();
~explosionhandler();
void registerexplosion(int& ttype,ALLEGRO_BITMAP*& b,int seq, float a, float m,float e);
void createexplosion(int ttype,float x,float y);
void drawexplosions(ALLEGRO_BITMAP* screen);
void gettype(explosion_type& a,ALLEGRO_BITMAP*& b,int& nseq, float& aa, float& ee, float& mm);
};#endif
explosionhandler.cpp:
explosionhandler::explosionhandler()
{
num_types=0;
}
void explosionhandler::registerexplosion(int& ttype,ALLEGRO_BITMAP*& b,int seq, float a, float m,float e)
{
explosion_type n;
....
ttype = num_types; /*********** right here *******************/
num_types++;
type.push_back(n);
}
explosionhandler passed as pointer to object rocket:
rocket.h:
...
class explosionhandler;
class rocket {
public:
...
void setrocket(ALLEGRO_BITMAP*& a,ALLEGRO_BITMAP*& b, explosionhandler*& h);
...
int exptype;
...
}; #endif
rocket.cpp:
rocket::rocket()
{
...
exptype=-1;
}
void rocket::setrocket(ALLEGRO_BITMAP*& a,ALLEGRO_BITMAP*& b, explosionhandler*& h)
{
handler = h;
area.sethitboundaries(a);
fprintf(stdout,"setrocket, # of rockets in vector: %i\n",(int)rockets.size());
h->registerexplosion(exptype,b,3,(float)al_get_bitmap_width(b),(float)0,(float)-18); //called function
}
and finally main.cpp (abbreviated):
#include "rocket.h"
#include "explosionhandler.h"
#include <allegro5/allegro.h>
#include <allegro5/allegro_image.h>
#include <stdio.h>
#include <cstdlib>
#define PI 3.14159265
...
rocket rock(bullet_speed+2,width,height);
explosionhandler *handler;
...
int setup()
{
...
rock.setrocket(rk,exp,handler);
rock.setlimit(5);
al_set_target_bitmap(al_get_backbuffer(display));
...
}
...
Ok Yeah its clear now the problem was handler was not initialized. whoops.
and of course explosionhandler is a pointer in main.cpp, rocket is an object declared in main.cpp, both are globals.
Bless my little noob heart I know not what I do.
My psychic sense tells me that you're calling rocket::setrocket with a NULL pointer as the parameter h (or more specifically, a reference to a NULL pointer), and then you're calling h->registerexplosion() on the NULL pointer.
Don't do that. Pass in a valid pointer instead, or allocate a new object (making sure you delete it properly later).