如何在公共lisp/cffi中使用windows句柄调用本机c函数

如何在公共lisp/cffi中使用windows句柄调用本机c函数,windows,lisp,common-lisp,sbcl,cffi,Windows,Lisp,Common Lisp,Sbcl,Cffi,本机c标头: typedef HANDLE HCAMERA; int Begin(HCAMERA* h); int End(HCAMERA h); 句柄定义为: 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 "came

本机c标头:

typedef HANDLE HCAMERA;
int Begin(HCAMERA* h);
int End(HCAMERA h);
句柄定义为:

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*))

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

你可以得到如下地址:

(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;
};

可能的陷阱:如果我使用Emacs中的lisp代码,我看不到C中的stdout。我使用
sbcl--script file.lisp从命令行执行它。希望,这对您有所帮助。

我最终通过以下代码找到了答案:

(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))))
(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))))