#Convert Type

26 messages · Page 1 of 1 (latest)

rich coyote
#

what is the code throwing the error?

toxic mica
#

Alright, so, your problem is that cpython gave you a "string" in the way they're typically represented in C: as a char*: a pointer to a null-terminated array of bytes.

#

Do you know how long the string is?

#

If so, you can convert it to a rust string (specifically, a &str), which you can print

#

We need an exact length for this

#

If you don't have it, you can compute it, but I'd be surprised if cpython doesn't have a way to get the length of a string

#

...Is there python code actively changing the length of the string?

#

If so, you cannot print it. You can't read something while someone else writes to it.

#

Can you guarantee that at least the length will stay constant until your GetName function returns?

#

Alright, that's good

rich coyote
toxic mica
#

If you can get the length, do this:

let len = get_length_somehow
let str: &str = core::str::from_raw_parts(pointer.cast::<u8>(), len);

If you can't, you'll have to scan the string looking for a terminating 0 byte (I don't know if one exists, double check your API's docs) counting as you go. Using CStr's APIs will do this for you, so you can do that

#

Not that easily

#

But you can do your conversion in a couple more lines

#

...Just write the couple more lines

#

Put them in a helper functions if you need

#

No need for a macro

#

We're not C, you don't have to aggressively make all small functions into macros instead

#

Oh wait, you're right, sorry

#

use std::slice::from_raw_parts, then use str::from_utf8 to get a Rust string. Also, double check what encoding python strings use

#

That to_str method does not exist, to my knowledge

rich coyote
#

don't listen to me, I'm out of my depth here -- I was just suggesting something which presumably doesn't work

toxic mica
#

You've mixed up my suggestion and theirs

rich coyote
#

I've tried to replicate what you've got going on and follow the compiler errors -- can you see if this line works rust CStr::from_ptr(Result).to_str().expect("Result isn't a valid string!"); instead of rust Result.to_string();
the library you're using looks pretty awful, even for ffi. My condolances

rich coyote
#

this is assuming you want it as an actual rust &str, but if you want to keep it as a CStr you can leave off .to_str()