我有这个C代码:
typedef struct {
double dat[2];
} gsl_complex;
gsl_complex gsl_poly_complex_eval(const double c[], const int len, const gsl_complex z);
C函数返回一个完整的结构,而不仅仅是一个指针,所以我不能将Raku声明写为:
sub gsl_poly_complex_eval(CArray[num64] $c, int32 $len, gsl_complex $z --> gsl_complex)
is native(LIB) is export { * }
有什么建议吗?
答案 0 :(得分:5)
为此,您需要一个CStruct。 P5localtime模块包含一个更详细的示例。
答案 1 :(得分:0)
一些C API使用一种三相方法来处理结构,通过引用传递结构,如下所示:
struct mystruct *init_mystruct(arguments, ...);
double compute(struct mystruct *);
void clean_mystruct(struct mystruct *);
这样,实现隐藏了数据结构,但这要付出代价:最终用户必须跟踪其指针,并记住自己清理一下,否则程序会泄漏内存。
另一种方法是我正在接口的库:将数据返回堆栈,因此可以将其分配给auto
变量,并在超出范围时自动将其丢弃。
在这种情况下,API被建模为两阶段操作:
struct mystruct init_mystruct(arguments, ...);
double compute(struct mystruct);
该结构按值传递到堆栈上,此后无需清理。
但是Raku的NativeCall接口只能使用C结构通过引用传递它们,因此出现了问题。
这不是一个干净的解决方案,因为它可以追溯到所描述的第一种方法,即三个阶段,但这是我到目前为止唯一能够设计的方法。
在这里,我考虑了库API的两个C函数:第一个创建一个复数作为结构,第二个将两个数加起来。
首先,我写了一个很小的C代码接口,文件complex.c:
#include <gsl/gsl_complex.h>
#include <gsl/gsl_complex_math.h>
#include <stdlib.h>
gsl_complex *alloc_gsl_complex(void)
{
gsl_complex *c = malloc(sizeof(gsl_complex));
return c;
}
void free_gsl_complex(gsl_complex *c)
{
free(c);
}
void mgsl_complex_rect(double x, double y, gsl_complex *res)
{
gsl_complex ret = gsl_complex_rect(x, y);
*res = ret;
}
void mgsl_complex_add(gsl_complex *a, gsl_complex *b, gsl_complex *res)
{
*res = gsl_complex_add(*a, *b);
}
我是这样编译的:
gcc -c -fPIC complex.c
gcc -shared -o libcomplex.so complex.o -lgsl
请注意用于链接我正在连接的libgsl C库的最后一个-lgsl
。
然后,我写了Raku底层界面:
#!/usr/bin/env raku
use NativeCall;
constant LIB = ('/mydir/libcomplex.so');
class gsl_complex is repr('CStruct') {
HAS num64 @.dat[2] is CArray;
}
sub mgsl_complex_rect(num64 $x, num64 $y, gsl_complex $c) is native(LIB) { * }
sub mgsl_complex_add(gsl_complex $a, gsl_complex $b, gsl_complex $res) is native(LIB) { * }
sub alloc_gsl_complex(--> gsl_complex) is native(LIB) { * }
sub free_gsl_complex(gsl_complex $c) is native(LIB) { * }
my gsl_complex $c1 = alloc_gsl_complex;
mgsl_complex_rect(1e0, 2e0, $c1);
say "{$c1.dat[0], $c1.dat[1]}"; # output: 1 2
my gsl_complex $c2 = alloc_gsl_complex;
mgsl_complex_rect(1e0, 2e0, $c2);
say "{$c2.dat[0], $c2.dat[1]}"; # output: 1 2
my gsl_complex $res = alloc_gsl_complex;
mgsl_complex_add($c1, $c2, $res);
say "{$res.dat[0], $res.dat[1]}"; # output: 2 4
free_gsl_complex($c1);
free_gsl_complex($c2);
free_gsl_complex($res);
请注意,我必须显式释放我创建的三个数据结构,从而破坏了原始的C API精心设计。