3

I've been on google for about, oh, 3 hours looking for a solution to this "problem." I'm trying to figure out how to instantiate a C structure in lisp using CFFI. I have a struct in c:

struct cpVect{cpFloat x,y;}

Simple right? I have auto-generated CFFI bindings (swig, I think) to this struct:

(cffi:defcstruct #.(chipmunk-lispify "cpVect" 'classname)
    (#.(chipmunk-lispify "x" 'slotname) :double)
    (#.(chipmunk-lispify "y" 'slotname) :double))

This generates a struct "VECT" with slots :X and :Y, which foreign-slot-names confirms (please note that I neither generated the bindings or programmed the C library (chipmunk physics), but the actual functions are being called from lisp just fine).

I've searched far and wide, and maybe I've seen it 100 times and glossed over it, but I cannot figure out how to create a instance of cpVect in lisp to use in other functions.

Note the function:

cpShape *cpPolyShapeNew(cpBody *body, int numVerts, cpVect *verts, cpVect offset)

Takes not only a cpVect, but also a pointer to a set of cpVects, which brings me to my second question: how do I create a pointer to a set of structs?

I've been to http://common-lisp.net/project/cffi/manual/html_node/defcstruct.html and tried the code, but get "Error: Unbound variable: PTR" (I'm in Clozure CL), not to mention that looks to only return a pointer, not an instance.

I'm new to lisp, been going pretty strong so far, but this is the first real problem I've hit that I can't figure out. Thanks!

1
  • Works for collections of pointers...half the problem. Thank you!!
    – andrew
    Jan 2, 2011 at 1:44

2 Answers 2

1

Most Common Lisp implementations do not allow passing structures on stack. There is a fsbv library which uses libffi to add that capability. If you know the structure layout you can decompose it manually as a series of basic arguments, but that is obviously brittle.

1
  • Turns out I didn't need to allocate on the stack after all, but your answer led me to dig deeper. Thank you.
    – andrew
    Jan 2, 2011 at 1:46
1

Not sure this will help much, but you could look at the ruby FFI bindings for chipmunk: https://github.com/shawn42/chipmunk-ffi/blob/master/lib/chipmunk-ffi/vec2.rb

Chipmunk has a data section that has all the inline method calls so FFI can use them. One of those is called cpv. cpv is the method that creates the cpVect struct. Feel free to start up a conversation about this on github w/ me (shawn42).

1
  • Turns out the CFFI binding is actually broken out so each time a cpVect is required, you pass vect-x and vect-y as separate arguments (solves the problem of creating on the stack). As far as allocating pointers, CFFI is working great.
    – andrew
    Jan 2, 2011 at 1:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.