从 Julia 更新 C 结构的字段值 [英] Updating a field value of a C struct from Julia
问题描述
我的问题很简单,但我不知道最好的方法(或者 Julia 目前不提供这种方法):如何从 Julia 设置 C 结构的字段值?
My question is simple but I don't know the best way to do that (or Julia doesn't offer such a way at the moment): how can I set a field value of a C struct from Julia?
假设您有一个结构类型来表示 C 库中树的节点:
Imagine you have a struct type to represent a node of a tree in a C library:
typedef struct node_s
{
int type;
node_t* next;
node_t* children;
node_t* parent;
} node_t;
并将其复制到 Julia 中:
and copy it in Julia:
immutable node_t
typ::Cint
next::Ptr{node_t}
children::Ptr{node_t}
parent::Ptr{node_t}
end
现在假设您在 C 中分配了一个指向 node_t
的指针,并且想要更新 Julia 中的 parent
字段.我知道我们有 unsafe_store!
来更新指针指向的值,但是计算 parent
字段的指针偏移量很麻烦(在这种情况下,它将是 sizeof(Int) + sizeof(Ptr{node_t}) * 2
在我的 64 位机器上).有没有更简单的方法来做同样的事情?
Now assume that you have a pointer to node_t
allocated in C and want to update the parent
field in Julia. I know we have unsafe_store!
to update a value pointed by a pointer, but it's cumbersome to calculate the pointer offset of the parent
field (in this case, it would be sizeof(Int) + sizeof(Ptr{node_t}) * 2
on my 64-bit machine). Is there any simpler way to do the same thing?
推荐答案
为这个用例提供了fieldoffset
函数:
The fieldoffset
function is provided for this use case:
julia> immutable node_t
typ::Cint
next::Ptr{node_t}
children::Ptr{node_t}
parent::Ptr{node_t}
end
julia> fieldoffset(node_t, 1)
0x0000000000000000
julia> fieldoffset(node_t, 2)
0x0000000000000008
julia> fieldoffset(node_t, 3)
0x0000000000000010
julia> fieldoffset(node_t, 4)
0x0000000000000018
但也不必担心简单地存储整个不可变
,只更改一个字段;它将被优化掉.
But also don't be worried about simply storing the whole immutable
, with one field changed; it will be optimized away.
julia> k = Ptr{node_t}(Libc.malloc(sizeof(node_t)))
Ptr{node_t} @0x00000000036194c0
julia> unsafe_load(k)
node_t(29544064,Ptr{node_t} @0x3038662d34363a34,Ptr{node_t} @0x3a386e2d3832313a,Ptr{node_t} @0x34363a32333a3631)
julia> update_parent(x::node_t, n::Ptr{node_t}) =
node_t(x.typ, x.next, x.children, n)
update_parent (generic function with 1 method)
julia> mutate!(k) = unsafe_store!(k, update_parent(unsafe_load(k), Ptr{node_t}(0)))
mutate! (generic function with 1 method)
julia> @code_llvm mutate!(k)
define %node_t* @"julia_mutate!_70963"(%node_t*) #0 {
top:
%1 = load %node_t, %node_t* %0, align 1
%.fca.3.insert = insertvalue %node_t %1, %node_t* null, 3
store %node_t %.fca.3.insert, %node_t* %0, align 1
ret %node_t* %0
}
这篇关于从 Julia 更新 C 结构的字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!