Need a working example of Firefox ctypes output string parameter
Hi I have an XPCOM component which I'm now converting to us开发者_Python百科e ctypes.
I was able to create functions that take a wchar_t* and I define the functions using ctypes.jschar.ptr. This all works great, but how do I use output parameters when I need to create wchar_t pointers and array of pointers?
I have done a lot of reading and I'm confused.
- How should I allocate the memory inside my C dll? should I use malloc? if so how would that get freed up?
- How would you allocate and handle an out parameter of wchar_t * ? would I pass it in from javascript as a CData I declate before?
- How should I handle a wchar_t string array?
Can anyone give me some code examples of say how to handle a function like this? (both on the C side of things, using malloc? or what should I use to allcoate the memory and on the javascript side, how this should be handled)?
int MyFunc(wchar_t** outString, wchar_t*** outStringArray)
Thanks!
I think I can help with your second question.
On the C side, your method which accepts an output parameter looks like:
const char* useAnOutputParam(const char** outParam) {
const char* str = "You invoked useAnOutputParam\0";
const char* outStr = "This is your outParam\0";
*outParam = outStr;
return str;
}
And on the JavaScript side:
Components.utils.import("resource://gre/modules/ctypes.jsm");
/**
* PlayingWithJsCtypes namespace.
*/
if ("undefined" == typeof(PlayingWithJsCtypes)) {
var PlayingWithJsCtypes = {};
};
var myLib = {
lib: null,
init: function() {
//Open the library you want to call
this.lib = ctypes.open("/path/to/library/libTestLibraryC.dylib");
//Declare the function you want to call
this.useAnOutputParam = this.lib.declare("useAnOutputParam",
ctypes.default_abi,
ctypes.char.ptr,
ctypes.char.ptr.ptr);
},
useAnOutputParam: function(outputParam) {
return this.useAnOutputParam(outputParam);
},
//need to close the library once we're finished with it
close: function() {
this.coreFoundationLib.close();
}
};
PlayingWithJsCtypes.BrowserOverlay = {
/*
* This is called from the XUL code
*/
doSomething : function(aEvent) {
myLib.init();
//Instantiate the output parameter
let outputParam = new ctypes.char.ptr();
//Pass through the address of the output parameter
let retVal = myLib.useAnOutputParam(outputParam.address());
alert ("retVal.readString() " + retVal.readString());
alert ("outputParam.toString() " + outputParam.readString());
myLib.close();
}
};
This forum post helped: http://old.nabble.com/-js-ctypes--How-to-handle-pointers-and-get-multiple-values-td27959903.html
精彩评论