Destructors for foreign objects

54 views
Skip to first unread message

Deepankar Sharma

unread,
Aug 17, 2024, 10:38:21 AM8/17/24
to chez-scheme
Is there a way to trigger some cleanup for a foreign object when it is collected? I made the following example to illustrate what I am looking for 

Given the following C++ code - 

########## lib.cpp ###############
#include <cstdlib>
#include <iostream>

struct StatefulObject {

  ~StatefulObject() {
    std::cout << "Destructor called." << std::endl;
  }
};

extern "C" {
  StatefulObject* build_struct() {
    return new StatefulObject();
  }
}
######## end lib.cpp ############

Built in this way - 
g++ -shared -fPIC -o libquestion.so lib.cpp


And accessed via chez FFI in the following manner

########### main.scm ##########
(import (chezscheme))

(load-shared-object "./libquestion.so")

(define build-struct
  (foreign-procedure "build_struct" () void*))

(collect)
(let
    ((ptr (build-struct)))
  (printf "Allocated object in let\n"))
(collect)
########## END main.scm ##########

Is there some way to have the C++ destructor be called when gc cleans up ptr? Maybe via some kind of registered finalizer?

I have some prior experience with the Python FFI and in that world they have the following functionality tp_dealloc. Am wondering if there is a chez equivalent.

Aldo Nicolas Bruno

unread,
Aug 17, 2024, 12:57:48 PM8/17/24
to Deepankar Sharma, chez-scheme
You will need make-guardian (see https://www.scheme.com/csug8/smgmt.html)
You will need to create a delete_struct in C and wrap it in chez, and then call it from the guardian, and you will also need to define a type for your struct pointer with define-ftype.
You can find some examples in my repo https://github.com/ovenpasta/thunderchez and probably in many other library bindings.

Aldo



---- On Sat, 17 Aug 2024 15:38:20 +0100 Deepankar Sharma <deepanka...@gmail.com> wrote ---

Deepankar Sharma

unread,
Aug 17, 2024, 2:21:10 PM8/17/24
to chez-scheme
Thank you for the pointers to guardian. It is exactly what I needed. 
Reply all
Reply to author
Forward
0 new messages