A
A
Atilla2013-10-22 03:09:18
C++ / C#
Atilla, 2013-10-22 03:09:18

Accessing a c++ method of an object from c

It is necessary to call the c++ method of the object from the c file, which is already declared and described in the c++ file.
The problem is that on the Internet I found only examples with method calls only for newly created objects (that is, those created in a wrapper file).

So, there is:
Actually cpp files with the desired object:
blah.h:

class blah {
  public:
  int	method (void);
}
extern blah object;


blah.cpp:
#include "blah.h"

int	blah::method (void) {
  ;
}
blah object;


Wrapper layer to access object.method() from c. For example, by calling the function wrapper_method ():
wrapper.h:
extern "C" int wrapper_method ( void ) ;


wrapper.cpp:
#include "wrapper.h"
#include "blah.h"

int wrapper_method ( void ) {
  return object.method ();
}


In this scenario, the linker cannot find the object object in wrapper.o.
Actually, how to be?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
E
evgeny_eJ, 2013-10-22
@evgeny_eJ

I recommend looking at the implementation of JNIEnv in jni.h.
From C, its methods are called like this: (*env)->callMethod(env, data)
From C++ like this: env->callMethod(data)

D
Door, 2013-10-22
@Door

First link for call c++ from c . Isn't it?

T
Teivaz, 2013-10-22
@Teivaz

Try to bind the function in the wrapper using boost::bind or std::mem_fun

boost::bind<blah>(&blah::method, &obj);

std::mem_fun<void, blah>(&blah::method);

D
degs, 2013-11-13
@degs

Everything links fine (gcc-4.6)

iBolit# make
g++    -c -o blah.o blah.cc
g++    -c -o wrap.o wrap.cc
cc    -c -o main.o main.c
cc   blah.o wrap.o main.o   -o blah
iBolit# ./blah
Blah!
iBolit# 
I specifically made main.c to check the link between C and C ++ modules, everything works. Most likely you have something wrong in the compilation / linking process, for example, the blah.o file was undeservedly forgotten during linking.
Actually there was an error in the code, missing ; after the blah class declaration in the blah.h file, but this gives an error when compiling and not linking.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question