Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling C++ static member functions from C code

Tags:

c++

c

I have a bunch of C code. I have no intention to convert them into C++ code.

Now, I would like to call some C++ code (I don't mind to modify the C++ code so that they are callable by C code).

class Utils {
public:
    static void fun();
}

class Utils2 {
public:
    static std::wstring fun();
}

If I tend to call them with the following syntax, they wont compiled (I am using VC++ 2008, with C code files with .c extension)

Utils::fun();
// Opps. How I can access std::wstring in C?
Utils2::fun();

Any suggestion?

like image 826
Cheok Yan Cheng Avatar asked Jul 07 '10 08:07

Cheok Yan Cheng


People also ask

How do you call a static member function?

We are allowed to invoke a static member function using the object and the '. ' operator but it is recommended to invoke the static members using the class name and the scope resolution operator.

How are static members accessed in C?

It can be accessed by any member function of the class. Normally, it is accessed with the class scope operator. If it is private, use a static member function to read or write it.

How do you access a static function?

Like static data members, you may access a static member function f() of a class A without using an object of class A . The compiler does not allow the member access operation this->si in function A::print_si() because this member function has been declared as static, and therefore does not have a this pointer.

Can I call static function from another file C?

In C, we can declare a static function. A static function is a function which can only be used within the source file it is declared in. So as a conclusion if you need to call the function from outside you do not define the function as static .


1 Answers

// c_header.h
#if defined(__cplusplus)
extern "C" {
#endif

void Utils_func();
size_t Utils2_func(wchar_t* data, size_t size);

#if defined(__cplusplus)
}
#endif
//eof

// c_impl.cpp
// Beware, brain-compiled code ahead!
void Utils_func()
{
  Utils::func();
}

size_t Utils2_func(wchar_t* data, size_t size)
{
  std::wstring wstr = Utsls2::func();
  if( wstr.size() >= size ) return wstr.size();
  std::copy( wstr.begin(), wstr.end(), data );
  data[wstr.size()] = 0;
  return str.size();
}
//eof
like image 59
sbi Avatar answered Sep 25 '22 21:09

sbi