Avión
Avión

Reputation: 8396

Trying to send parameters from a simple Python function to C++

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.

Upvotes: 1

Views: 130

Answers (1)

akluth
akluth

Reputation: 8583

This line

    void Foo_bar(Foo* foo){ foo->bar(int number); }

seems pretty wrong. int number would be a variable decleration, but you want to give a variable as a parameter to a method. For this purpose, it needs to be in the method definition of Foo_bar.

Try:

    void Foo_bar(Foo* foo, int number){ foo->bar(number); }

and in your Python code

def bar(self, number):
    lib.Foo_bar(self.obj, number)

Upvotes: 2

Related Questions