Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Calling C++ methods from C

Status
Not open for further replies.

ambili

Programmer
Aug 22, 2001
9
US
Hi,

I have some applications using a common library. These applications are written in C. I like to rewrite the library in C++. Is it feasible to do so? What can be the main overhead of doing it so. Now this library is written in C.

Thanks in advance,
ambili
 
There should be no difference. C++ will have no problems calling any C Funcitons.

Matt
 
Hi,

Thanks for your reply. I think my question was not clear. Now the library and the applications are written in C. This library provides some API's that different application uses.
I like to rewrite this library from C to C++. I know for providing all the API's I need to write a wrapper over my C++ classes. But I like to know whether this is a good decision. What can be the overhead and limitation if I do so.

Thanks,
Ambili
 
to write wrappers is when you're using C objects, and wrappers are used for simplier using of them. Also you can write wrappers for using C++ classes from C.
for example

class xxx
{
public:
int write(){cout<<&quot;xxx&quot;<<endl;return 0;}
};
the wrapper will be
xwrite(void* handle)//handle is supposed to be xxx* type
{
return((xxx*)handle)->write();
}
Ion Filipski
1c.bmp


filipski@excite.com
 
Hi,
Thanks for your help. I know how to write the wrapper over C++ classes. But need to know whether these library can be used by an application which is written in C.And what can be the limitations if i do so.

Thanks
Ambili
 
see C++ implementation, like I do it in VisualC++. In GCC should be some similar. You will compille it in C++. In C programs use the .h file and the resulted object file as implementation, not the .cpp. Declarations between
#ifdef __cplusplus and #endif will not be visible from C programs.
The limitation is what you will not be able to overwrite xwrite(void*) function. In my opinion it became a FAQ.

//classdecl.h
#if !defined(__CLASSDECL_H)
#define __CLASSDECL_H
#ifdef __cplusplus
class xxx
{
int write();
};
#endif
#ifdef __cplusplus
extern &quot;C&quot; {
#endif
extern int xwrite(void* handle);
#ifdef __cplusplus
}
#endif
#endif
//end of classdecl.h
//classdecl.cpp

#include&quot;classdecl.h&quot;
int xxx::write()
{
return 0;
}
int xwrite(void* handle)
{
return ((xxx*)handle)->write();
}
//end of classdecl.cpp
Ion Filipski
1c.bmp


filipski@excite.com
 
Thanks for your help Ion Filipski.

Ambili
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top