cogciprocate / ocl

OpenCL for Rust
Other
731 stars 75 forks source link

Help `u16` to `Char16` conversion #228

Closed Ote-Leo closed 7 months ago

Ote-Leo commented 7 months ago

I'm trying to learn OpenCL and I cannot figure out how to overcome this runtime error:

Kernel(
    ArgTypeMismatch {
        idx: 0,
        arg_name: "message",
        ty_name: "char16*",
        ty: ArgType {
            base_type: Char,
            cardinality: Sixteen,
            is_ptr: true
        }
    }
)

The original code is:

use ocl::{MemFlags, ProQue, Result};

const KERENL: &str = r#"

    __kernel void hello_kernel(__global char16* message) {
        *message = (char16) ( 'H', 'e', 'l', 'l', 'o', ' ', 'K', 'e', 'r', 'n', 'e', 'l', '!', '!', '!', '\0' );
    }

"#;

pub fn run() -> Result<()> {
    let pro_que = ProQue::builder().src(KERENL).dims(1).build()?;
    let length = "Hello Kernel!!!".len() + 1;

    let buffer = pro_que
        .buffer_builder::<u16>()
        .flags(MemFlags::WRITE_ONLY)
        .len(length)
        .build()?;

    let kernel = pro_que
        .kernel_builder("hello_kernel")
        .arg(&buffer)
        .build()?;

    unsafe {
        kernel.enq()?;
    }

    let mut message = vec![0u16; length];
    buffer.read(&mut message).enq()?;

    let message = String::from_utf16_lossy(&message);
    println!("Found Message: {message}");

    Ok(())
}

fn main() {
    run().unwrap();
}
c0gent commented 7 months ago

You want a vector of u8 not u16. Characters are 8 bits. In case it was confusing, the 16 in char16 just means the length of the vector (so 16 x 8 total bits per vector in this case).

Ote-Leo commented 7 months ago

Oh thanks, I fixed it

use ocl::{MemFlags, ProQue, Result};

const KERNEL: &str = r#"

    __kernel void hello_kernel(__global uchar16* message) {
        *message = (uchar16) ( 'H', 'e', 'l', 'l', 'o', ' ', 'K', 'e', 'r', 'n', 'e', 'l', '!', '!', '!', '\0' );
    }

"#;

pub fn run() -> Result<()> {
    let pro_que = ProQue::builder().src(KERNEL).dims(1).build()?;

    let buffer = pro_que
        .buffer_builder::<u8>()
        .flags(MemFlags::WRITE_ONLY)
        .len(16)
        .build()?;

    let kernel = pro_que
        .kernel_builder("hello_kernel")
        .arg(&buffer)
        .build()?;

    unsafe {
        kernel.enq()?;
    }

    let mut message = [0u8; 16];
    buffer.read(message.as_mut_slice()).enq()?;
    let message = String::from_utf8_lossy(&message);
    println!("Found Message: {message}");

    Ok(())
}

fn main() {
    run().unwrap();
}