简体   繁体   中英

Issue in Compling C++ method in Eclipse and calling C++ method from python

Simple C++ example class I want to talk to in a file called foo.cpp

#include <iostream>

Since ctypes can only talk to C functions, you need to provide those declaring them as extern "C"

extern "C" {
    Foo* Foo_new(){ return new Foo(); }
    void Foo_bar(Foo* foo){ foo->bar(); }
}

class Foo{
    public:
        void bar(){
            std::cout << "Hello" << std::endl;
        }
};

compile this to a shared library

g++ -c -fPIC foo.cpp -o foo.o
g++ -shared -Wl,-soname,libfoo.so -o libfoo.so  foo.o

finally I have wrote python wrapper

from ctypes import cdll lib = cdll.LoadLibrary('./libfoo.so')

class Foo(object):
      def __init__(self):
          self.obj = lib.Foo_new()

      def bar(self):
          lib.Foo_bar(self.obj)
f = Foo()
f.bar() #prints "Hello" on the screen

"My main intension is to compile C++ code in eclipse and call the C++ function from python in Linux". This works fine when I compiled C++ code in Linux and call the C++ method from python in Linux. But it doesn't work if I compile C++ code in eclipse and call the C++ method from python in Linux.

Error message:

symbol not found

I am new to the eclipse tool chain, But I am giving compiler option and linking option in as in this
g++ -c -fPIC foo.cpp -o foo.o g++ -shared -Wl,-soname,libfoo.so -o libfoo.so foo.o

Snapshot of eclipse compiler option and linking option will be highly appreciated. Please help me in sorting out this issue. Thanks in advance

You need to create two projects in the Eclipse.

  1. Makefile project with existing code. ( File->New->Makefile project with existing code ). In this project you must point to your foo.cpp file. Then in the project folder you must create file which name is "Makefile". Makefile must contain folowing lines:

    all:

    g++ -c -fPIC foo.cpp -o foo.o

    g++ -shared -W1,-soname,libfoo.so -o libfoo.so foo.o

    clean:

    rm -f libfoo.so

Then You must create rules ("all" and "clean") for this project in the "Make Target" window. If you don't see this window You must do Window->Show view->Make Target . Thus you can create libfoo.so file using Eclipse when double-clicked on the "all" rule in the "Make target" view.

  1. At this moment You can create PyDev project with foo.py file. If you don't know about PyDev you must go to this site . It is Eclipse plugin for python language. When you will have installed this plugin You will can to work with your python file under the Eclipse.

See some images. 在此输入图像描述 在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM