Note that there are some explanatory texts on larger screens.

plurals
  1. POctypes class member access segfaulting
    text
    copied!<p>I'm interested in using a c++ class in python. Looking at <a href="https://stackoverflow.com/questions/145270/calling-c-c-from-python">Calling C/C++ from python?</a>, I decided to try ctypes. However, I get segfault when I try to change the value of a class member.</p> <p>Here is a simple example that reproduce my problem:</p> <p>The C/C++ side:</p> <pre><code>#include &lt;iostream&gt; class Foo{ private: int mValue; public: void bar(){ std::cout &lt;&lt; "Hello" &lt;&lt; std::endl; } void setValue(int inValue) { mValue = inValue; std::cout &lt;&lt; "Value is now: " &lt;&lt; mValue &lt;&lt; std::endl; } void setValue2() { mValue = 2; std::cout &lt;&lt; "Value is now: " &lt;&lt; mValue &lt;&lt; std::endl; } }; extern "C" { Foo* Foo_new(){ return new Foo(); } void Foo_bar(Foo* foo){ foo-&gt;bar(); } void Foo_setValue(Foo* foo, int v) { foo-&gt;setValue(v); } void Foo_setValue2(Foo* foo) { foo-&gt;setValue2(); } } </code></pre> <p>The code is compile on OSX with:</p> <pre><code>g++ -c -fPIC foo.cpp -o foo.o &amp;&amp; g++ -shared -Wl -o libfoo.dylib foo.o </code></pre> <p>The python side:</p> <pre><code>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); </code></pre> <p>I can call bar without problem, but I get segfault if I call set or set2.</p> <pre><code>f = Foo() f.bar() # Ok f.set(3) # Segfault </code></pre> <p>Obviously, I'm missing something. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload