Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pass a void pointer to be allocated in a C function #34

Closed
GedorN opened this issue Apr 30, 2024 · 6 comments
Closed

Pass a void pointer to be allocated in a C function #34

GedorN opened this issue Apr 30, 2024 · 6 comments

Comments

@GedorN
Copy link

GedorN commented Apr 30, 2024

I'm trying to use a function in C to pass a pointer, have it allocated and modified in C, and then retrieve this modified pointer in Node.js. However, I'm unable to do it at all. Can you help me?

C function:

extern "C" int32_t alloc_pointer(int32_t **c) {
    *c = (int32_t *)malloc(3 * sizeof(int32_t));
    if (*c == NULL) {
        return -1; 
    }

    (*c)[0] = 1;
    (*c)[1] = 2;
    (*c)[2] = 3;

    return 0;
}

Node example:

 let ret = createPointer({
    paramsType: [DataType.I32Array],
    paramsValue: [[]]
  })


  const v = load({
    library: "libsum",
    funcName: 'alloc_pointer', 
    retType: DataType.I32,
    paramsType: [DataType.External],
    paramsValue: ret
  });

  const unwrapPtr = restorePointer({
    paramsValue: ret,
    retType: [DataType.I32Array],
  })
@zhangyuang
Copy link
Owner

I will see it later

@zhangyuang
Copy link
Owner

try with this code

const i32Ptr = createPointer({
    paramsType: [DataType.I32Array],
    paramsValue: [[-1, -1, -1]]
  })[0]

  const v = load({
    library: "libsum",
    funcName: 'alloc_pointer',
    retType: DataType.I32,
    paramsType: [DataType.External],
    paramsValue: [i32Ptr]
  });
  const unwrapPtr = restorePointer({
    paramsValue: [i32Ptr],
    retType: [arrayConstructor({
      type: DataType.I32Array,
      length: 3
    })],
  })
  console.log('111', unwrapPtr)

@GedorN
Copy link
Author

GedorN commented Apr 30, 2024

It worked! But do I need to know the size of the array that was allocated to use restorePointer and to create the pointer? I will need to work with Buffer and won't know what size it will be allocated.

@zhangyuang
Copy link
Owner

There's no good way if you don't know the length of array, because restore array data by offset pointer is unsafe, we must guarantee the address to which the pointer point is valid.

I will also think whether there has other way to implement this feature

@zhangyuang
Copy link
Owner

An interim solution is create a big and fixed length space to store the return data

@GedorN
Copy link
Author

GedorN commented May 27, 2024

I really appreciate the help.

@GedorN GedorN closed this as completed May 27, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants