Trying to send parameters from a simple Python function to C++ -
i'm trying link python script c++ script. found , 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 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 execute just:
python foowrapper.py
this works, prints me 'test!' of bar() function.
the thing want send parameters python function c++ function i've tried doesnt work.
this 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 error. trying compile c++ function:
foo.cpp: in function ‘void foo_bar(foo*)’: foo.cpp:13: error: expected primary-expression before ‘int’ what i'm doing wrong? in advance.
this line
void foo_bar(foo* foo){ foo->bar(int number); } seems pretty wrong. int number variable decleration, want give variable parameter method. purpose, needs in method definition of foo_bar.
try:
void foo_bar(foo* foo, int number){ foo->bar(number); } and in python code
def bar(self, number): lib.foo_bar(self.obj, number)
Comments
Post a Comment