View mode: basic / threaded / horizontal-split · Log in · Help
November 14, 2012
Coverting ubyte to string.
Hi

I am working with a c library which return a unsigned char *

As suggested on http://digitalmars.com/d/1.0/htomodule.html

I have converted it to (ubyte *).

Now is there an easy way to convert this to a string ?

Knud
November 14, 2012
Re: Coverting ubyte to string.
On Wednesday, 14 November 2012 at 13:37:26 UTC, Knud Soerensen 
wrote:
> Hi
>
> I am working with a c library which return a unsigned char *
>
> As suggested on http://digitalmars.com/d/1.0/htomodule.html
>
> I have converted it to (ubyte *).
>
> Now is there an easy way to convert this to a string ?

import std.conv;
void main() {
    char[] s = "aoeu\0".dup;
    ubyte* bs = cast(ubyte*)s.ptr;

    // If you know the length, you can use a slice
    char[] s2 = cast(char[])bs[0..s.length];
    // this includes \0
    assert(s == s2);
    // but you could of course have used s.length-1

    // or you can walk and look for \0
    char[] s3 = to!(char[])(s.ptr);
    // note that to doesn't keep the zero terminator
    assert(s3 == s[0..$-1]);
}
November 14, 2012
Re: Coverting ubyte to string.
This might help.

import std.c.string;

void main() {
  // The input data:
  ubyte* ustr = cast(ubyte*) "bobcat\0".ptr;

  // Conversion to 'string'.
  char* cstr = cast(char*) ustr;
  string str = cast(string) cstr[0..strlen(cstr)];
  assert(str == "bobcat");
}

 - Vijay

On Wednesday, 14 November 2012 at 13:37:26 UTC, Knud Soerensen 
wrote:
> Hi
>
> I am working with a c library which return a unsigned char *
>
> As suggested on http://digitalmars.com/d/1.0/htomodule.html
>
> I have converted it to (ubyte *).
>
> Now is there an easy way to convert this to a string ?
>
> Knud
Top | Discussion index | About this forum | D home