Skip to content

Instantly share code, notes, and snippets.

@allwefantasy
Created April 21, 2019 02:32
Show Gist options
  • Save allwefantasy/e4d774742fb6961b4805c70432158469 to your computer and use it in GitHub Desktop.
Save allwefantasy/e4d774742fb6961b4805c70432158469 to your computer and use it in GitHub Desktop.

I have desigh a Ctensor.

#[repr(C)]
pub struct CTensor {
    data: *const c_float,
    data_length: c_int,
    shape: *const c_int,
    shape_length: c_int,
}

and provide a function to create this struct:

#[no_mangle]
pub extern "C" fn create_tensor(data: *const c_float,
                                data_length: c_int,
                                shape: *const c_int,
                                shape_length: c_int, ) -> *mut CTensor {
    let ctensor = CTensor {
        data,
        data_length,
        shape,
        shape_length,
    };

    println!("create_tensor data: {:?} len:{:?}", unsafe { *ctensor.data }, ctensor.data_length);
    println!("create_tensor shape: {:?} len:{:?}", unsafe { *ctensor.shape }, ctensor.shape_length);

    Box::into_raw(Box::new(ctensor))
}

Then I call create_tensor in C side:

CTensor *xTensor = create_tensor(xP, 1, shape_x_p, 1);
CTensor *yTensor = create_tensor(yP, 1, shape_y_p, 1);

printf("-----%s------\n", "jack coo");
printf("CTensor in c data:%f len:%i \n", xTensor->data, xTensor->data_length);
printf("CTensor in c shape:%f len:%i \n", xTensor->shape, xTensor->shape_length);

In rust side, the resul is right:

create_tensor data: 1.0 len:1
create_tensor shape: 1 len:1
create_tensor data: 2.0 len:1
create_tensor shape: 1 len:1

But in C side, it's not work:

CTensor in c data:0.000000 len:-327289448
CTensor in c shape:0.000000 len:-327289476

And i still do no get point why it not work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment