是否有一种官方方法可以将通过引用传递的参数转换为完全相同的类型?我知道在编译的 CodeGen 阶段,ref int
会变成 int *
,并且我知道您可以使用 extern 来做到这一点。为了 C 互操作性,但是为了编写 Chapel 抽象呢?此外,宽引用和宽指针的情况又如何呢?你会如何处理这样的事情。
对于那些好奇的人,我正在尝试一些 PGAS-STM(分区全局地址空间 - 软件事务内存),我需要做的事情之一就是允许语义如下......
使用 STM 添加到列表前面:
// Global variables
var head : node(eltType);
// Local variables
var newHead = new node(eltType);
var retry = false;
var stm = manager.getDescriptor();
do {
retry = false;
try! {
stm.begin();
// Takes pointer of 'head' via its reference...
// What happens if its a wide reference???
var h = stm.read(head);
newHead.next = h;
stm.write(head, nextHead);
stm.commit();
} catch retry : STMRetry {
retry = true;
}
} while retry;
是的,它目前很难看,但它是一个非常早期的原型(prototype)。
编辑:将 STMBegin
的命名更改为 begin
最佳答案
Is there an official way to convert an argument passed by reference to a pointer to the exact same type?
我不知道“官方”,但我的直觉是尝试使用 c_ptrTo
如下,这似乎从 Chapel 1.16 开始工作。给定这些文件:
testit.chpl:
extern proc bar(x: c_ptr(int));
require "testit.h";
var i = 42;
foo(i);
writeln("after foo, i is: ", i);
proc foo(ref x: int) {
var c_ptr_to_x: c_ptr(int) = c_ptrTo(x);
bar(c_ptr_to_x);
writeln("after bar, x is: ", x);
x = 22;
}
testit.h:
#include <stdint.h>
#include <stdio.h>
#include <inttypes.h>
static void bar(int64_t* x) {
printf("bar got: %"PRId64"\n", *x);
*x = 32;
}
结果似乎如我所愿:
$ chpl testit.chpl
$ ./testit
bar got: 42
after bar, x is: 32
after foo, i is: 22
what about for the sake of writing Chapel abstractions?
我认为 c_ptr()
类型实际上只是为了与 C 进行互操作,而不是作为在 Chapel 本身内编写基于指针的抽象的一种方法。
Furthermore, what about the case of wide references and wide pointers?
这些是实现概念,而不是在语言级别向最终用户公开的抽象,因此我不确定 Chapel 中是否有规定的用户级方法来处理这些类型。
关于stm - 将 Chapel 中的 'ref dataType' 参数转换为 'ptr(dataType)',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49176517/