I am attempting to use ctypes to share a C++ object with Python, by creating the object in C++, and passing the pointer out to Python via a C wrapper. I want to be able to act on this object later using the other functions in the Python class, do_something
in the code below.
I've tried the following code, but I get a segfault. I'm new to interfacing C with C++ and C with Python, so I'm not sure if I'm doing something fundamentally wrong when passing the pointer, or if the memory is being cleared/shifted by Python garbage-collection, after I create the object?
This question discusses a similar problem for boost, but the answer isn't very useful for ctypes.
object.h
class object {
public:
// constructor
object() {
pointer = nullptr;
}
// destructor
virtual ~object() {
delete pointer;
pointer = nullptr;
}
// get member functions of object_pointer
// from C++
double do_something();
protected:
// pointer to the object
object_pointer *pointer;
};
extern "C" {
object* object_new();
void object_delete(object *Ob);
double object_do_something(object *Ob);
}
object.cpp
#include "object.h"
double object::do_something() { return pointer->do_something(); }
extern "C" {
object *object_new() { return new object(); }
void object_delete(object *Ob) { delete Ob; }
double object_do_something(object *Ob) { return Ob->do_something(); }
}
object.py
from ctypes import *
lib = cdll.LoadLibrary('./lib_object.so')
lib.object_new.argtypes = ()
lib.object_new.restype = c_void_p
lib.special_delete.argtypes = c_void_p,
lib.special_delete.restype = None
lib.object_pointer.argtypes = c_void_p
lib.object_pointer.restype = c_void_p
class Object:
def __init__(self):
self.obj = lib.object_new()
print self.obj
def __del__(self):
lib.object_delete(self.obj)
def do_something(self):
lib.object_do_something(self.obj)
s = Object()
>> 94549743086144
s.do_something()
>> Segfault
Any help would be greatly appreciated!