MFC: How to use C++ Global Object in C
I have an MFC application in which I have declared a Global Object say "obj" in a file called MiRec2PC.cpp now I want to use this object in a C file.
I have used an approach in which I include the header file in which the structure of that particular object is declared. I also use a keyword "extern" with that obj when I use it . but still the compiler is showing a link error:
LINK : warning LNK4098: defaultlib "LIBCMT" conflicts with use 开发者_C百科of other libs; use /NODEFAULTLIB:library httpApplication.obj : error LNK2001: unresolved external symbol _m_iRecordInst Debug/MiRec2PC.exe : fatal error LNK1120: 1 unresolved externals Error executing link.exe. Creating browse info file... MiRec2PC.exe - 2 error(s), 12 warning(s)
Regards
Umair
You cannot access classes from C++ in C without some sort of indirection and/or interface. If you really want to use it in C (Why?) then you will have to devise some kind of extern "C" interface to your object.
E.g. implement some cinterface.h:
#ifdef __cplusplus
extern "C" {
#endif
// It does not have to be void* but at this point it is the easiest thing to use.
typedef void * ObjCType;
ObjCType obj_get_obj (void);
int obj_get_value(ObjCType);
#ifdef __cplusplus
};
#endif
And then in cinterface.cpp implement the C language interface delegating to the Obj's member functions.:
#include <obj.hpp>
#include <cinterface.h>
// This is defined somewhere else.
extern Obj obj;
ObjCType obj_get_obj ()
{
return &obj;
}
int obj_get_value(ObjCType o)
{
return static_cast<Obj*>(o)->get_value ();
}
And finally, use the C interface in your source.c:
#include <cinterface.h>
int main ()
{
ObjCType o = obj_get_obj ();
int x = obj_get_value (o);
}
精彩评论