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
© 2024 OneMinuteCode. All rights reserved.