I'm converting Audio Queues Service code into swift3.2 but i got stuck here.i don't know how to write this line of code in swift updated version.
I want to convert below code into swift 3.2
player.packetDescs = UnsafeMutablePointer<AudioStreamPacketDescription>(malloc(sizeof(AudioStreamPacketDescription) * Int(player.numPacketsToRead)))
where player object is :
class Player {
var playbackFile: AudioFileID? = nil
var packetPosition: Int64 = 0
var numPacketsToRead: UInt32 = 0
var packetDescs: UnsafeMutablePointer<AudioStreamPacketDescription>? = nil
var isDone = false
}
I tried this :
let j = MemoryLayout.size(ofValue: AudioStreamPacketDescription.self) * Int(player.numPacketsToRead)
player.packetDescs = UnsafeMutablePointer<AudioStreamPacketDescription>(malloc(j))
But this give me error :
Cannot invoke initializer for type
'UnsafeMutablePointer' with an argument
list of type '(UnsafeMutableRawPointer!)'
ok Try this
let sizeTmp = MemoryLayout.size(ofValue: AudioStreamPacketDescription.self) * Int(player.numPacketsToRead)
let tmpPointer = UnsafeMutablePointer<AudioStreamPacketDescription>.allocate(capacity: sizeTmp)
player.packetDescs = tmpPointer
Related
I have code that uses precisionEvaluate() on a session variable, but when I call the function, there is this error :
Element emp_nextid_ANE_801 is undefined in a Java object of type class
coldfusion.runtime.J2eeSessionScope.
In the code, there is a condition to check this session variable with structKeyExists(), but it still shows an error. Does anyone know why it still errors?
Here is some of the code :
if( structKeyExists(session,'emp_nextid_#app().getCurrentAgentID()#_#officeID#')
AND val(session['emp_nextid_#app().getCurrentAgentID()#_#officeID#']) GT 0) {
var nextID = precisionEvaluate(session['emp_nextid_#app().getCurrentAgentID()#_#officeID#']);
var qData = new Query();
var sql = "SELECT 1 FROM Employee
WHERE pers_id = :nextid";
qData.addParam(name="nextid", value=nextID, cfsqltype="CF_SQL_BIGINT");
var result = qData.execute(sql=sql).getResult();
}
The call, app().getCurrentAgentID(), might be generating values that are changing dynamically. In any case, you can improve the code snippet to:
var key = 'emp_nextid_' & app().getCurrentAgentID() & '_' & officeID;
if( structKeyExists(session,key) AND val(session[key]) GT 0) {
var nextID = precisionEvaluate(session[key]);
...
etc.
}
Starting with a class definition as follows:
class Player {
var playbackFile: AudioFileID? = nil
var packetPosition: Int64 = 0
var numPacketsToRead: UInt32 = 0
var packetDescs: UnsafeMutablePointer<AudioStreamPacketDescription>? = nil
var isDone = false
}
Then defining a callback function:
let AQOutputCallback: AudioQueueOutputCallback = {(inUserData, inAQ, inCompleteAQBuffer) -> () in
let aqp = UnsafeMutablePointer<Player>(inUserData).pointee // this gives an error
// more code
}
This results in an error on the second line: "Cannot invoke initializer for type 'UnsafeMutablePointer' with an argument list of type 'UnsafeMutableRawPointer?'
How do I properly cast from type 'UnsafeMutableRawPointer?' to 'UnsafeMutablePointer' in Swift 3?
The following modification eliminated the error:
let aqp = inUserData!.assumingMemoryBound(to: Player.self).pointee
to convert MutableRawPointer to object, we use fromOpaque api
/// Unsafely turns an opaque C pointer into an unmanaged class reference.
///
/// This operation does not change reference counts.
///
/// let str: CFString = Unmanaged.fromOpaque(ptr).takeUnretainedValue()
///
/// - Parameter value: An opaque C pointer.
/// - Returns: An unmanaged class reference to `value`.
public static func fromOpaque(_ value: UnsafeRawPointer) -> Unmanaged<Instance>
example:
var info:UnsafeMutableRawPointer = ....
let obj = Unmanaged<$AnyObject>.fromOpaque(info).takeUnretainedValue()
I'm using the Node.js ffi addon to call a C++ DLL.
The problem I'm having is with the struct I'm supplying - it contains a char array - I don't believe I'm setting this up correctly.
As a result I am unable to access the contents.
Routine's definition from C++ header file:
int GetSysConfig(MyConfig * config);
The MyConfig struct is defined in C++ as follows:
typedef struct{
int attribute;
char path[256];
}MyConfig;
My corresponding Node.js struct definition:
var ffi = require('ffi');
var ref = require('ref');
var StructType = require('ref-struct');
var ArrayType = require('ref-array');
// This seems to be the problematic part?
var charArray = ArrayType('char');
charArray.length = 256;
var MyConfig = StructType({
'attribute' : 'int',
'path' : charArray
})
Note: Below here is where I call the DLL from Node.js - I don't think there's a problem here although I could be wrong.
// Create a pointer to the config - we know we expect to supply this to the C++ routine.
var myConfigPtr = ref.refType(MyConfig);
var lib = ffi.Library('my.dll', {
"GetSysConfig": ["int", [myConfigPtr]]
});
var myConfigObj = new MyConfig();
lib.GetSysConfig.async(myConfigObj.ref(), function(err, res) {
console.log("attribute: " + myConfigObj.attribute);
// This is always empty [] - when it shouldn't be.
console.log("path: " + JSON.Stringify(myConfigObj.path));
});
Does anyone know where I'm going wrong with this?
For structs containing arrays: These should be defined with their size specified as a parameter to ArrayType.
For example:
ArrayType('char', 256)
Therefore the fix for my problem is the following:
var MyConfig = StructType({
'attribute' : 'int',
'path' : ArrayType('char', 256)
})
SCardTransmit function is defined in https://msdn.microsoft.com/en-us/library/windows/desktop/aa379804%28v=vs.85%29.aspx
I want to declare and use this function, I have problems with the definition of some arguments in js-ctypes (especially in type casting):
LPCSCARD_IO_REQUEST: A pointer to the protocol header structure
LPCBYTE: A pointer to the actual data to be written to the card
LPBYTE: Pointer to a 32-byte buffer that receives the ATR string from the currently inserted card, if available. (this arg is in the status function)
How Can define, initialize and use them?
Here my code:
//-----------------define types----------------------
Cu.import('resource://gre/modules/ctypes.jsm');
var TYPES = {
ABI: is64bit ? ctypes.default_abi : ctypes.winapi_abi,
DWORD: ctypes.uint32_t,
LONG: ctypes.long,
BYTE: ctypes.unsigned_char //ctypes.uint8_t
};
TYPES.LPDWORD = TYPES.DWORD.ptr;
TYPES.SCARDCONTEXT = TYPES.ULONG_PTR;
TYPES.SCARDHANDLE = TYPES.ULONG_PTR;
TYPES.LPBYTE = TYPES.BYTE.ptr;
var CONST = {
SCARD_PROTOCOL_T0: 0x00000000,
SCARD_PROTOCOL_T1: 0x00000001
}
const SCARD_IO_REQUEST = new ctypes.StructType("myStruct" ,
[{"dwProtocol": TYPES.DWORD},
{"cbPciLength": TYPES.DWORD}]);
//------------------declaration-------------------------
var SCardTransmit = cardLib.declare('SCardTransmit', TYPES.ABI, TYPES.LONG, TYPES.SCARDHANDLE, SCARD_IO_REQUEST.ptr, TYPES.LPBYTE, TYPES.DWORD, SCARD_IO_REQUEST.ptr, TYPES.LPBYTE, TYPES.LPDWORD);
//------------------initializing---------------------
var _SCARD_IO_REQUEST = new SCARD_IO_REQUEST;
_SCARD_IO_REQUEST.dwProtocol = CONST.SCARD_PROTOCOL_T0|CONST.SCARD_PROTOCOL_T1;
_SCARD_IO_REQUEST.cbPciLength = _SCARD_IO_REQUEST.dwProtocol.toString().length;
var command = ctypes.char.array(42)("00a4040010a0000000183003010000000000000000");
var commandLength = command.toString().length;
var response = TYPES.LPBYTE;
var responseLength = TYPES.LPDWORD;
//----------------using-------------------------
var rez_SCT = SCardTransmit(cardHandle, _SCARD_IO_REQUEST, command, commandLength, null, response, responseLength.address());
if(rez_SCT.toString() != CONST.SCARD_S_SUCCESS.toString())
{
console.error('cannot begin transaction, error code was: ' + rez_SCT + ' in other terms it is: 0x' + rez_SCT.toString(16) + ' you can look up this error value here: https://msdn.microsoft.com/en-us/library/windows/desktop/aa374738%28v=vs.85%29.aspx#smart_card_return_values');
throw new Error('failed to begin transactio!');
}
Ok! I have a flashVar variable that is coming into Flash, its URL encoded but I have already decoded it. My problem is I want the set of variables to be pushed into an array.
Let's say the variables are
"&text0=Enter Text...&size0=18&font0=Arial&color0=0&rotation0=0&y0=360&x0=640&text1=Enter
Text...&size1=18&font1=Arial&color1=0&rotation1=0&y1=360&x1=640"
and so on...
What I want is the variables to go into an array like
myArray[0].text = Enter Text...
myArray[0].size = 18]
myArray[0].font = Arial
myArray[0].color = 0
myArray[0].rotation = 0
myArray[0].y = 360
myArray[0].x = 640
myArray[1].text = ...........
.............................
.............................
myArray[n].text = ...........
I think there must be some way to do this. Most probably I'm thinking regular expression, but I'm pretty bad at regular expression. Please some help would be very very appreciated.
Thank You!
You don't have to decode your query string, just use the URLVariables object - it will do all the decoding for you. Then iterate over its dynamic properties to create your array. Use a RegExp to find the index numbers at the end of your variable keys:
function parseURLVariables( query:String ) : Array {
var vars:URLVariables = new URLVariables (query);
var arr:Array = [];
for (var key : String in vars) {
var splitIndex : int = key.search(/[0-9]+$/);
var name:String = key.substr (0,splitIndex);
var indexNumber:int = parseInt ( key.substr(splitIndex));
arr[indexNumber] ||= {};
arr[indexNumber][name] = vars[key];
}
return arr;
}
Since your query string starts with a an ampersand, you might have to use parseURLVariables ( myString.substr(1)), otherwise the URLVariables object will throw an error, complaining that the query string is not valid (it has to be url encoded, and start with a variable key).
you may use split method of string to something like this;
var astrKeyValue: Array = url.Split( "&" );
in this way each value in astrKeyValue is string keyvalue ( for example font1=Arial )
after than you may split each item with "=" and will get pair key and value ( for key - font1 and for value - arial)
so this code maybe will work for you
var str = "text0=Enter Text...&size0=18&font0=Arial&color0=0&rotation0=0&y0=360&x0=640&text1=Enter Text...&size1=18&font1=Arial&color1=0&rotation1=0&y1=360&x1=640"
var a : Array = str.split( "&" );
var newArr: Array = new Array()
for each ( var str1 in a )
{
var t: Array = str1.split( "=" );
newArr[ t[0] ] = t[1];
}
trace( newArr.text0 ) // -> Enter Text...
Here is a solution for you from me,
//your string data should be like this, there should be a seperate seperator (i've used pipe sign |) for each element which will be converted to an object and then pushed to the array
var strData:String = "text=Enter Text...&size=18&font=Arial&color=0&rotation=0&y=360&x=640|text=Enter Text...&size=18&font=Arial&color=0&rotation=0&y=360&x=640";
var myArray:Array = new Array();
var _tmpArr:Array = strData.split("|");
//populating the array
for(var i:int=0;i<_tmpArr.length;i++)
{
myArray.push(strToObj(_tmpArr[i]));
}
trace(myArray.length);
// coverts chunk of string to object with all key and value in it
function strToObj(str:String):Object
{
var obj:Object = new Object();
var tmpArr:Array = str.split('&');
for (var i:int = 0; i < tmpArr.length; i++)
{
var _arr:Array = String(tmpArr[i]).split('=');
var key:String = String(_arr[0]);
var val:String = String(_arr[1]);
obj[key] = val;
trace(key+" = "+val);
}
trace("----");
return obj;
}