在Racket中C浮点数的正确指针类型转换是什么?

问题描述 投票:1回答:1

在Racket文档中有整数指针类型,如_intptr,但是如何使用float * from,比方说,动态C库?

lisp racket
1个回答
4
投票

Racket内置_float(和_double)C型表示,还有_pointer类型。您可以将这些结合起来将返回值视为C float指针。

沿着这些方向的东西(这是一个草图 - 根据您的情况根据需要进行修改):

你的C函数:

float* my_float_returner() {
    float* pi = malloc(sizeof(float));
    *pi = 3.1415926535;
    return pi;
}

和Racket FFI包装:

(require ffi/unsafe
         ffi/unsafe/define)

;; not strictly necessary, but probably a good reminder for yourself
(define _float-ptr _pointer)

;; registers the library and sets up the function to define interfaces to its contents
(define-ffi-definer define-my-lib (ffi-lib "my_library_path"))

;; defines the interface to your C function
(define-my-lib my_float_returner (_fun -> _float-ptr))

;; returns a _float object containing the dereferenced value returned by
;; my_float_returner
(ptr-ref (my_float_returner) _float)

毋庸置疑,以这种方式将指针视为无类型可能是危险的,你必须要小心。

我甚至会引用Racket foreign function interface documentation的第一句话:

虽然使用FFI不需要编写新的C代码,但它对C程序员面临的与安全和内存管理相关的问题几乎没有隔离。

如果你使用这些工具,你应该打开你的C帽,与所有指针相关 偏执 随之而来的关怀和体贴。

© www.soinside.com 2019 - 2024. All rights reserved.