I am interested in using a C ++ class in python. Looking for calling C / C ++ from python? I decided to try ctypes. However, I get segfault when I try to change the value of a class member.
Here is a simple example that reproduces my problem:
Side C / C ++:
#include <iostream> class Foo{ private: int mValue; public: void bar(){ std::cout << "Hello" << std::endl; } void setValue(int inValue) { mValue = inValue; std::cout << "Value is now: " << mValue << std::endl; } void setValue2() { mValue = 2; std::cout << "Value is now: " << mValue << std::endl; } }; extern "C" { Foo* Foo_new(){ return new Foo(); } void Foo_bar(Foo* foo){ foo->bar(); } void Foo_setValue(Foo* foo, int v) { foo->setValue(v); } void Foo_setValue2(Foo* foo) { foo->setValue2(); } }
The code compiles on OSX with:
g++ -c -fPIC foo.cpp -o foo.o && g++ -shared -Wl -o libfoo.dylib foo.o
Python side:
from ctypes import * lib = cdll.LoadLibrary('./libfoo.dylib') class Foo(object): def __init__(self): self.obj = lib.Foo_new() def bar(self): lib.Foo_bar(self.obj) def set(self, v): lib.Foo_setValue(self.obj, v); def set2(self): lib.Foo_setValue2(self.obj);
I can call the bar without problems, but I get segfault if I call set or set2.
f = Foo() f.bar()
Obviously I'm missing something.
source share