How to operate on TypedArray in C++

Asked by ben layet

I would like to know how in Duetto C++ to use a TypedArray from, for example, a binary XmlHttpRequest or a Canvas ImageData object. I see notes on using MakeTypedArray to convert from, say, a char* to a TypedArray so I can pass it to a Browser API. How do I do the reverse. How can I convert a TypedArray to a char*, for example? I don't want to do a copy.

thanks
ben

Question information

Language:
English Edit question
Status:
Solved
For:
Cheerp Edit question
Assignee:
No assignee Edit question
Solved by:
ben layet
Solved:
Last query:
Last reply:
Revision history for this message
Alessandro Pignotti (a-pignotti) said :
#1

Hi Ben,

there is no specific API at the moment to do a copy-less conversion, although we have plan to add it soon. In duetto 0.9.6 and the upcoming 1.0 release you can use the following hack to access a typed array like a plain pointer:

        Int8Array* ar=new Int8Array(4);
        char* volatile c=(char*)(Array*)ar;
        c[2] = 42;

Please be careful in using the right C data type for any given typed array to guarantee correct results. The apparently useless double cast is necessary. Again, we plan to add a cleaner solution in future, but this should work and no copy is made.

Revision history for this message
ben layet (layetb) said :
#2

Thanks, that looks suitable for use with Browser APIs within the C++. What if I want to pass TypedArrays to a C++ method from the JS? What signature do I need on the C++ method?

e.g. I want to do:

In JS
var obj = new Object();
var input_array = some typed array;
var output_array = some typed array;
obj.method(input_array, output_array);

In C++
class Object [[jsexport]] {
public:
  void method(<what signature here?>) {
      <use C pointers to access the TypedArrays here>
   }

ben

Revision history for this message
Alessandro Pignotti (a-pignotti) said :
#3

You can use two different approaches:

1) Use client::Int8Array (or any typed array) and convert to pointer to data on the C++ side, like shown above
2) Forge a duetto compatible pointer on the javascript side, using the following syntax
     obj.method( { d: input_array, o: 0}, { d:output_array, o: 0})

Revision history for this message
ben layet (layetb) said :
#4

I used 2) above - and a C++ signature of void method(unsigned char*, unsigned char*).