Accessing struct members in CFFI

Discussion of Common Lisp

Accessing struct members in CFFI

Postby joeish80829 » Wed Oct 09, 2013 6:10 am

Here is the opencv code i'm trying to convert to lisp

int size[] = { 5, 5, 5 };
CvMatND* b = cvCreateMatND(3, size, CV_32F);
int a=0;
for (int x = 0; x < b->dim[0].size; x++)
for (int y = 0; y < b->dim[1].size; y++)
for (int z = 0; z < b->dim[2].size; z++)
{ a++;
cvSet3D(b, x,y,z, cvScalar(a));


in the code above it creates a 3 dimensional matrix and adds data to it in the for loop
in the loop the code accesses the sizes of each dimension of the 3d matrix with dim[0].size dim[1].size and dim[2].size
I'm trying to do the same in lisp....I created wrappers for the structs and the c function below and tried everything i could from nested with-foreign-slots to access the members of dim to mem-reffing and mem-areffing the out put of dims....the most i got was a plist for dim (STEP 100 SIZE 5) when i accessed the cv-mat-nd-dim struct with with-foreign-slots inside a with-foreign-slots for MATRIX i set with this

(defparameter matrix (create-mat-nd 3 '(5 5 5 ) +32fc1+))

but it has only 1 item in it, in c you can access an infinite number because its an nd matrix

(cffi:defcunion cv-mat-nd-data
(ptr :pointer)
(fl :pointer)
(db :pointer)
(i :pointer)
(s :pointer))

(cffi:defcstruct cv-mat-nd-dim
(size :int)
(step :int))

;; ;(cffi:foreign-type-size '(:struct cv-mat-nd)) = todo - doesn't work cv-mat-nd = 40 opencv's = 288
(cffi:defcstruct cv-mat-nd
(type :int)
(dims :int)
(refcount :pointer)
(hdr-refcount :int)
(data (:union cv-mat-nd-data))
(dim (:pointer (:struct cv-mat-nd-dim))))

;; CvMatND* cvCreateMatND(int dims, const int* sizes, int type)
(cffi:defcfun ("cvCreateMatND" %create-mat-nd) (:pointer (:struct cv-mat-nd))
"Creates the header and allocates the data for a multi-dimensional dense array."
(dims :int)
(sizes :pointer)
(type :int))

(defun create-mat-nd (dims sizes type)
"Return a specific element of single-channel nD array."
(%create-mat-nd dims
(cffi:foreign-alloc :int :initial-contents sizes) type))
Posts: 95
Joined: Tue Sep 03, 2013 5:32 am

Re: Accessing struct members in CFFI

Postby nuntius » Thu Oct 10, 2013 9:10 pm

When dealing with foreign memory, you often have to use the full foreign API.

Is there a reason you are not wrapping "cvSet3D" and using that in CFFI?
User avatar
Posts: 497
Joined: Sat Aug 09, 2008 10:44 am
Location: Burlington, MA

Re: Accessing struct members in CFFI

Postby joeish80829 » Fri Oct 11, 2013 8:12 am

I have Set3D wrapped ,i'm in the process of wrapping all of opencv (c) , but can you help me access the dimension data in the dim struct member in c it seems to be an array with as many elements as there are matrix dimensions
Posts: 95
Joined: Tue Sep 03, 2013 5:32 am

Return to Common Lisp

Who is online

Users browsing this forum: Bing [Bot] and 1 guest