Calling C/C++ on Python

Asked 2 years ago, Updated 2 years ago, 26 views

I want to use C/C++ libaray in Python, how can I bind it?

c python c++

2022-09-21 19:39

1 Answers

Let me show you an example. If you want to use the next foo.cpp in Python,

foo.cpp)

#include <iostream>

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

Python's ctype can only be accessed C function, so write external "C" (you don't have to do it in C))

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

Now compile foo.cpp into shared library

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

Now you can write code on the 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()

Results)

 Hello


2022-09-21 19:39

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.