`Namestr` only has space for the first character (::Uint8), so only the
first character is copied. With the struct hack, the string is stored
inline so you have to read the length first in order to know how many
characters to copy.

Something like this should work (one version of `bytestring` takes a length
argument):

```
namePtr = ccall(dlsym(clib, :makename), Ptr{Uint8}, (Ptr{Uint8},), bob)  #
note Uint8 return value to work with bytes

len = unsafe_load(reinterpret(Ptr{Int32}, namePtr)) # get the length
bytestring(namePtr + 4, len)
```






On Tue, Jun 10, 2014 at 1:46 AM, Ben Alex <[email protected]> wrote:

> I have just started with Julia and need to invoke an external C library
> that has used the "struct hack <http://c-faq.com/struct/structhack.html>"
> to represent a string. How do I retrieve the string in Julia? I've ported
> the example from the linked FAQ entry and tried this code:
>
> immutable Name
>   Namelen::Int32
>   Namestr::Uint8
> end
>
> const clib = dlopen("libstructtest")
>
> bob = convert(Ptr{Uint8}, "Bob")
> namePtr = ccall(dlsym(clib, :makename), Ptr{Name}, (Ptr{Uint8},), bob)
> name = unsafe_load(namePtr)
>
> println(name.Namelen)
> println(name.Namestr)
>
> This code will display the ASCII code of the first character (65=B), but
> how do you iterate over the remainder? I've also tried other approaches
> including Namestr::Ptr{Uint8}, unsafe_load of the Namestr when a Pointer,
> bytestring etc. Any suggestions appreciated.
>
> Thanks
> Ben
>
>

Reply via email to