[gambit-list] FFI Converting std::vector to scheme-vector (best practice)
Chris Mueller
ruunsmail at gmail.com
Tue Aug 20 16:16:22 EDT 2013
On 20.08.2013 14:01, Mikael wrote:
> Waait. I didn't check but I'm not so sure it's supposed to work like
> that - I wonder why you had access to ___result_voidstar there at all.
Yep, that's interesting. You can even use it in another procedures that
expects a struct (it dereferences automatically the pointer).
In the documentation section 19.1 there are some interesting hints about
that.
* internal pointer points to a copy of c-data type.
* When an instance is converted from C to Scheme, a block of memory is
allocated from C Heap and initialized with that instance.
* After that a foreign-object is allocated from scheme-heap and
initialized via copy-constructor from the c object in g++.
* Deallocation of the copy on the C heap is under control of the release
function attached to the foreign object.
i don't know whether managing the c-copy is in responsibility of the
developer or the scheme compiler.
> Please allocate such a test structure *locally on the stack* within your
> struct-test procedure, and then set ___result to it. I.e., by value and
> not by pointer passing. Then paste here again.
Here's the new procedure:
(define struct-test
(c-lambda () struct-test "struct test x; ___result = x;"))
But if i run the test script with this function, i get a
segmentation fault immediately.
There is also another option which comes in my mind:
(define struct-test
(c-lambda () struct-test "struct test x; ___result_voidstar = &x;"))
This is e.g. running the allocation loop. But it will segfault when
quiting the script with CTRL + X.
I've currently work around this by explicitly setting the release
function with a simple c++ template.
typename <typename T> ___SCMOBJ release(void* ptr) {
delete ((T*) ptr); return ___FIX(___NO_ERR);
}
But it would be great, if we could clarify later the proper usage of
structs in the ffi. I've gotten curious about that. :)
More information about the Gambit-list
mailing list