【发布时间】:2017-06-19 20:17:26
【问题描述】:
我将我的应用程序嵌入到 Julia 中,我需要一种从 Julia 和 C++ 读取/写入相同结构的好方法。
在 Python 中我可以简单地做:
ffi.cdef("""
struct keyboard_s {
int forward;
int backward;
int left;
int right;
int jump;
}
struct keyboard_s *app_get_keyboard();
"""
app = ffi.dlopen("app.dll")
thekeyboard = app.app_get_keyboard();
thekeyboard.forward = 1; # this would immediatly change the memory in C
但是,我在 Julia 中尝试了类似的操作,而 Julia 总是只复制数据并且无法从 C 中更改外部内存地址:
type keyboard_s
forward::Int32
backward::Int32
left::Int32
right::Int32
jump::Int32
end
# lets imply this would return the memory struct just like app_get_keyboard()
# I just use malloc(sizeof(keyboard_s)) so everybody here can test for themselves...
address = ccall(:malloc, (Int64), (Int64, ), sizeof(keyboard_s))
# address is now a valid Int64 address, so lets map it as pointer of type keyboard_s
ptr = Ptr{keyboard_s}(address)
# thekeyboard contains now the random data from the c static memory
thekeyboard = unsafe_load(ptr)
# this will change only the value of "thekeyboard",
# it doesn't touch C the Int64 address memory pointer...
thekeyboard.forward = 123 # this has no effect on the real memory address :(
# lets load the keyboard again from same address
thekeyboard = unsafe_load(ptr)
thekeyboard.forward == 123 # this is false! no effect whatsoever in C memory from Julia
在 Julia 中我应该如何与 C 共享结构的内存地址?
【问题讨论】: