1

本机 c 标头:

typedef HANDLE HCAMERA;
int Begin(HCAMERA* h);
int End(HCAMERA h);

HANDLE 定义:

typedef void *HANDLE;

我想要的本机c源:

HCAMERA h;
int r = 0;
r = Begin(&h);
VERIFY(r);
r = End(h);
VERIFY(r);

我在 sbcl 1.3.1 中尝试了以下代码,但没有工作。

(cffi:use-foreign-library "camera.dll")

(cffi:defcfun "Begin" :int
  (handle :pointer))

(cffi:defcfun "End" :int
  (handle :pointer))

(defparameter *camera* (cffi:foreign-alloc :pointer)) ; alloc handle

(cffi:with-foreign-object (handle :pointer)
  (setf (cffi:mem-ref handle :pointer) *camera*) ; handle address
  (Begin handle)
  (End *camera*))

顺便说一句:如何获得外物(相机)的地址?我做对了吗?

4

2 回答 2

1

你可以得到这样的地址:

(defun get-foreign-address (obj)
  (write-to-string (cffi:pointer-address obj) :base 16))

如果你有这个 C 文件

#include <stdio.h>

typedef void *HANDLE;
typedef HANDLE HCAMERA;

int Begin(HCAMERA* h);
int End(HCAMERA h);

int Begin(HCAMERA* h) {
    printf("Address from Begin: %p\n", h);
    return 0;
};
int End(HCAMERA h) {
    printf("Address from End: %p\n", (void*)&h);
    return 0;
};

你可以看到,例如通过这个通用的 lisp 文件,你从 lisp 和 C 中获得了相同的地址handle*camera*因为它是按值传递的,所以不一样。我在Linux上试过了,但我认为在Windows上应该是一样的,只需更改camera.socamera.dll.

(cffi:use-foreign-library "camera.so")

(cffi:defcfun "Begin" :int
  (handle :pointer))

(cffi:defcfun "End" :int
  (handle :pointer))

(cffi:defcvar ("stdout" stdout) :pointer)

(defparameter *camera* (cffi:foreign-alloc :pointer))

(cffi:with-foreign-object (handle :pointer)
  (format t "Address from Lisp: ~a~%" (get-foreign-address handle))
  (Begin handle)
  (format t "Address from Lisp: ~a~%" (get-foreign-address *camera*))
  (End *camera*))

(cffi:foreign-funcall "fflush" :pointer stdout :int)

可能的陷阱:如果我使用 Emacs 中的这个 lisp 代码,我看不到 C 中的标准输出。我从命令行使用sbcl --script file.lisp. 希望,这会以某种方式帮助你。

于 2016-01-08T13:04:49.160 回答
0

我终于想通了使用以下代码:

(defparameter *camera-handle* (cffi:null-pointer))
(defun camera-open ()
  (unless (cffi:null-pointer-p *camera-handle*)
    (EndHVDevice (cffi:mem-ref *camera-handle* :pointer))
    (cffi:foreign-free *camera-handle*))
  (setf *camera-handle* (cffi:foreign-alloc :pointer))
  (BeginHVDevice *camera-handle*))

(defun camera-close ()
  (unless (cffi:null-pointer-p *camera-handle*)
    (EndHVDevice (cffi:mem-ref *camera-handle* :pointer))
    (cffi:foreign-free *camera-handle*)
    (setf *camera-handle* (cffi:null-pointer))))
于 2016-02-02T06:24:35.333 回答