Julia get wrong value when I try to unsafe_load a pointer from C -


the c code:

typedef struct __kstring_t {     size_t l, m;     char *s; } kstring_t;  kstring_t * get_ptr_of_kstr(int num){     char * ch = (char *)malloc(num);     kstring_t kstr = {0, num, ch};     kstring_t *p = &kstr;     printf("in c, kstr.l: %zu\n", p->l);     printf("in c, kstr.m: %zu\n", p->m);     printf("in c, kstr.s: %p\n", p->s);     printf("in c, pointer kstr: %p\n", p);     return p; }; 

the julia code

type kstr l::csize_t m::csize_t s::ptr{cchar} end 

problem

when use ccall call get_ptr_of_kstr , pointer of kstring_t in julia, use unsafe_load value, value seems wrong. messages below:

in c, kstr.l: 0 in c, kstr.m: 100000 in c, kstr.s: 0x37b59b0 in c, pointer kstr: 0x7fffe7d80b90 kstr = ptr{ht.kstr} @0x00007fffe7d80b90 unsafe_load(kstr).s = ptr{int8} @0x00007fffe7d80b90 

the value of unsafe_load(kstr).s same kstr. why? how fix it?

regarding c part (i don't know bindings between julia , c):

kstring_t kstr = {0, num, ch}; 

that allocate kstr on stack in get_ptr_of_kstr() context. , pointer return invalid right after function exits. can't use anymore after that, not in c or other program might pass to.

as @lutfullahtomak hinted, should either:

  • allocate heap malloc()/calloc(),
  • pass pre-allocated pointer function , fill members,
  • declare static in body of function, makes global variable scope reduced function only. note not practice though.

also, note c compiler align each struct member address, depending on options , #pragma pack (if used), offset of each field might not or julia expects.


Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -