Friday, 20 July 2018

how to work with references using ffi?

I have folowing c++ function compiled with node-gyp.
void InterfaceTestOne(const string & mytest)
{       
        const string *ptr = &mytest; 
        printf("The variable X is at 0x%p\n", (void *)ptr);
        cout << mytest.length() << endl;
        cout << mytest << endl;
}

and nodejs code:
var math = ffi.Library(main, {
    "_Z16InterfaceTestOneRKSsi": ["void",  [ref.refType(string)]],

});

var output = ref.allocCString('hello alex');

console.log("length", output.length) #12
console.log("address", output.address()) #4353704472
console.log("ref", output.ref()) # <Buffer@0x103804228 18 42 80 03 01 00 00 00>

math._Z16InterfaceTestOneRKSsi(output.ref(), outputText.length)

#c++ output
The variable X is at 0x0x103804230 
4347093136 <-- mytest size 
This is TestOne
hello alex�����s�P��X��0��
                           ����������������������p
p�]���^@��psp���5�����@4������(�����G����� ��qf���
6�ՃP���f���6�Ճ���q�X؃ \���u������������3������3������!Ą
p�?�����p                                                                                                
�J
����h����������8n���������8v
�d�����s����� ����������(������a......

So instead of string size 12 i got in c++ size 4353704472 ref address in nodejs and c++ also is difference 0x103804228 and 0x0x103804230. and looks that's why i got in addition to my text a ton of garbage.
Any idea how to fix that?


from how to work with references using ffi?

No comments:

Post a Comment