How to call native C code, using the js-ctypes Firefox extension?
Asked Answered
F

2

9

I am trying to build a Firefox extension, that needs to call native C code.

My C program code is:

#include<windows.h>
int add(int a, int b)
{
    return(a + b);
}

and my JavaScript code is :

var {Cu} = require('chrome');
var self  = require('sdk/self');
Cu.import("resource://gre/modules/ctypes.jsm");
var lib;
var puts;
lib = ctypes.open('G:\\Shankar\\Project\\Maidsafe\\Firefox\\addon-sdk-1.17\\jsctype_sample\\data\\Win32Project1.dll');

try {
    puts = lib.declare("add", /* function name */
        ctypes.default_abi, /* call ABI */
        ctypes.int32_t, /* return type */
        ctypes.int32_t, /* argument type */
        ctypes.int32_t /* argument type */
    );
} catch (e) {
    console.log('Érror'+ e);
}

function binaryFile() {        
    var ret = puts(1, 2);
    dump(ret);
    lib.close();
};

exports.binaryFile = binaryFile;

when calling the binaryFile function, I get the error

Couldn't find function symbol in library

Please help me out. tHanks in advance.

Faulk answered 9/2, 2015 at 13:29 Comment(1)
Shouldn't yout use int instead of int32_t?Dominican
F
6

Here is my repository where complete code is been available

Faulk answered 10/2, 2015 at 9:18 Comment(0)
M
5

If your addon is a restartless addon, make sure to set <em:unpack>true</em:unpack>. The addon MUST be unpacked.

Awesome, you're getting deep into addons! See this repo: https://github.com/Noitidart/fx-sapi-test That shows the code to main.cpp which is compiled into a DLL and then imported and used.

You have to expose your add function.

By the way, if you were doing a bootstrap addon: Also try doing the ctypes.open inside the startup() function. But you aren't, you're doing an Addon SDK addon, so you should be ok. But for your import do this:

lib = ctypes.open(self.data.url('Win32Project1.dll'));

That way you don't have to know the absolute path. Especially because \\ file seperator is only for Windows. Unix like systems (MacOSX, Linux, ...) use /.

If you need more help join the moz jsctypes IRC channel :)

Mannos answered 9/2, 2015 at 15:32 Comment(5)
Cheers for the shared links! Did help me it getting my stuff sorted :) Will connect on the channel with you to learn more on the Add-on. Have been breaking my head a lot more with XPCOM. Thanks again.Faulk
self.data.url('someFile.dll') in the ctypes.open give the error as couldn't open library resources://....Faulk
I myself solved it by using var dataUrl = self.data.url("udp_client.dll"); dataUrl = Services.io.newURI(dataUrl,null,null).QueryInterface(Ci.nsIFileURL).file.path;. ThanksFaulk
Awesome job there! Thanks for sharing!Mannos
This might help some one just like me. :)Faulk

© 2022 - 2024 — McMap. All rights reserved.