I'm trying to link a Python script with a C++ script. I found this and works.
foo.cpp
#include <iostream>
class Foo{
public:
void bar(){
std::cout << "Test!" << std::endl;
}
};
extern "C" {
Foo* Foo_new(){ return new Foo(); }
void Foo_bar(Foo* foo){ foo->bar(); }
}
fooWrapper.py
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()
To compile I use:
g++ -c -fPIC foo.cpp -o foo.o
g++ -shared -Wl,-soname,libfoo.so -o libfoo.so foo.o
If -soname doesn't work, use -install_name:
g++ -c -fPIC foo.cpp -o foo.o
g++ -shared -Wl,-install_name,libfoo.so -o libfoo.so foo.o
And to execute just:
python fooWrapper.py
This works, it prints me that 'Test!' of the bar() function.
The thing is that now I want to send some parameters from the Python function to the C++ function but what I've tried doesnt work.
This is my try:
foo.cpp
#include <iostream>
class Foo{
public:
void bar(int number){
printf("Number is: %d", number);
std::cout << "Test!" << std::endl;
}
};
extern "C" {
Foo* Foo_new(){ return new Foo(); }
void Foo_bar(Foo* foo){ foo->bar(int number); }
}
fooWrapper.py
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)
num = 5
f = Foo()
f.bar(num)
I get this error. Trying to compile the C++ function:
foo.cpp: In function ‘void Foo_bar(Foo*)’:
foo.cpp:13: error: expected primary-expression before ‘int’
What I'm doing wrong? Thanks in advance.