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.