0

I have a working python wrapper for C++ code (as suggested here Calling C/C++ from python? ) using ctypes. But the problem is with main function of the code. When I do something like

         extern "C" {
             void call_main(){ main();}
         }

in my c++ code and then call this function via python wrapper

            ...
            lib = cdll.lib('./mylib.so')
            def run():
                lib.call_main()

-> I get "segmentation fault".

The funny part is that when i copy paste my main method code into function called e.g. test (so it is int test() {....#pasted code...} in c++ code), extern it and then call lib.test()

=> And eveything works fine... So it must be a problem with the main function being called main or something

Community
  • 1
  • 1
kosta5
  • 1,129
  • 3
  • 14
  • 36

1 Answers1

2

In C++ calling main() recursively is not allowed ( see 3.6.1, basic.start.main, paragraph 3). Also, you need a C++ aware entry point when you want to call C++ functionality. You can sometimes get away with calling C++ functionality without this but what is going to work and what is not isn't entirely straight forward. The obvious problem is with global objects needing initialization.

Just put the code you want to call into a different function and call this.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • thanks ... can you point to me what you mean by "c++ aware entry point" ? – kosta5 Mar 09 '12 at 07:12
  • The operating system is pretty much oblivious of needs of different environments. All it does when starting a program is to jump to some place and start executing. This typically is some symbol from a start-up object (e.g. crt0.o). If yhis doesn't know about C++ it won't run constructors for global objects, for example. When linking via a C++ compiler you are OK but since you want to call the C++ main() it seems youmight not do this. – Dietmar Kühl Mar 09 '12 at 11:32