Page 1 of 1

Creating a pointer to a C string in CFFI

Posted: Tue Mar 18, 2014 8:45 pm
by joeish80829
I'm trying to recreate a const char* filename parameter for code I have that needs it...The function I'm wrapping is the OpenCV C++ function "imread" it is below in the documentation. It is used to read an image(jpg etc) from a file and return a pointer to it

Code: Select all

http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html?highlight=imread#imread
first I need to wrap in C as below calling the const char* filename parameter as a String*
the below cv_imread does compile on ubuntu trusty using g++. And the function works as intended using g++.

Code: Select all

Mat* cv_imread(String* filename, int flags) {
    return new Mat(cv::imread(*filename, flags));
}
I wrap in Lisp like this:

Code: Select all

(defcfun ("cv_imread" %imread) (:pointer mat)
  (filename (:pointer string*))
  (flags :int))
When I usually create a (:pointer string*) parameter I do it like this

Code: Select all

(window-name (foreign-alloc :string :initial-element "IMREAD Example"))

and it works to supply strings that aren't filenames but when I try to use a filename both absolute and relative paths it fails...it also fails using double forward slashes in the pathname.


Any advice is appreciated and btw Emacs /SBCL is my Lisp IDE

Re: Creating a pointer to a C string in CFFI

Posted: Wed Mar 19, 2014 4:19 pm
by Goheeca
You are using C++ and there is no char* (C-style string) in your wrapper. CFFI means C-style strings by :string. You must write your wrappper something like this:

Code: Select all

Mat* cv_imread(const char* filename, int flags) {
    return new Mat(cv::imread(string(filename), flags));
}
According to docs imread takes a reference to string.

Re: Creating a pointer to a C string in CFFI

Posted: Thu Mar 20, 2014 11:50 am
by joeish80829
I had new insight...your wrapper didn't work either btw, I added a cout line to the wrapper and saw iy was getting the correct filename so now I'm curious as to why when I run my lisp wrapper like this

(dp filename (foreign-alloc
:string :initial-element "/home/w/d1"))
(imread filename 1)


I get a Unhandled memory fault at #x24FFFFFFF8.
[Condition of type SB-SYS:MEMORY-FAULT-ERROR]

I'm on ubuntu trusty using SBCL,g++ in emacs

Re: Creating a pointer to a C string in CFFI

Posted: Thu Mar 20, 2014 1:16 pm
by pjstirling
Why aren't you calling the extern "C" wrapper named already in the library?

Code: Select all

CvMat* cvLoadImageM(const char* filename, int iscolor=CV_LOAD_IMAGE_COLOR )