Search code examples
c++clualuajit

Luajit and Torch7 : accessing objects of type cdata from the Torch7 C api


Is there a way to convert cdata to userdata? How can I use the C api to push/retrieve cdata to/from the stack?

Edit: The original title mentioned luajit but not Torch. In that context the other answers beside the one I finally had submitted myself (e.g wolfgang's) made perfect sense.


Solution

  • The cdata I was trying to access was the data of a tensor object from torch7, I finally found a way by using the torch7 C API, I will post it here just in case someone finds it useful:

    #include <TH/TH.HW>
    #include <TH/THStorage.h>
    #include <TH/THTensor.h>
    

    And then to get a tensor called "an_image" in the torch code:

    lua_getglobal(L,"an_image");//assuming it goes on top of the stack
    THDoubleTensor*data=(THDoubleTensor*)luaT_toudata(L,-1,"torch.DoubleTensor");
    

    And finally given a buffer dest of doubles,

    memcpy(dest,data->storage->data,n*sizeof(double));