Ctypes class member access segfaulting

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() # Ok f.set(3) # Segfault 

Obviously I'm missing something.

+4
source share
1 answer

Using the following solution to the problem:

 def __init__(self): lib.Foo_new.restype = c_void_p # Needed self.obj = lib.Foo_new() def set(self, v): lib.Foo_setValue(c_void_p(self.obj), v) # c_void_p needed 

Reading seems to be a 64-bit pointer problem.

+1
source

Source: https://habr.com/ru/post/1434906/


All Articles