How can I read data from COM object (an activex server) in MATLAB? - matlab

I am trying to connect a simulator to the MATLAB. The simulator program exposes a COM object interface.
I have connected to the COM object by the following command and can perform most of it methods:
h=actxserver(ProgID)
But some of its methods need passing of a Variant* type as output.
Here is the signature of one of the methods indicated by "invoke" method:
ReadOutputImage=Variant(Pointer) ReadOutputImage(handle, int32, int32, `ImageDataTypeConstants, Variant(Pointer))`
I have called this method with several syntax's, but none of them work:
a=uint8([0]) %means unsigned integer array with 1 member
h.ReadOutputImage(0,1,2,a) % 0 ,1 ,2 are contants pointing to the position, number of elements to read and size of elemnts while 2 shows Byte element (VT_UI2 COM type).
Other syntax's that I have tried and has no result are: using uint16, uint32, int8, int16, int32 for all of the followings:
logical types (like a=[false]),
cell arrays (like a={uint8([0])} )
empty cell array {}
empty array []
empty sring ''
I have used libpointer as well:
a=libpointer;
also a=libpointer('uint8Ptr',0)
also a=libpointer('bool',false)
also a=libpointer('bool',[0])
The problem is that I am not sure about the following items:
What is the similar type of " Variant(Pointer) " in MATLAB?
What is the method of passing a variable as output to a COM method in MATLAB?
Is it even possible to get a value from a COM object method result as a pointer in MATLAB?
To find how the data appears in other clients, I have imported the same dll file into Delphi and the signature of the type library for the above method is like this:
procedure ReadOutputImage(StartIndex: Integer; ElementsToRead: Integer;
DataType: ImageDataTypeConstants; var pData: OleVariant);
Yes Siemens has provided a guide for this com server (prosim) and based on such documentation I have connected and performed most of its methods. But the methods which read I/o data are not working. In documentation the method signature is specified as follows: (in VB)
STDMETHOD(CS7Prosim::ReadOutputImage)(long startindex,long elementstoread, imagedatatypeconstants DtaType, VARIANT* pData)
What about your application, was it working? Did it contains variant pointers as the returning argument? Did you have simillar methods in that application?
Thank you

I can help with #2 in your question. I just worked through this myself. Basically, any pass by reference to COM object you to access after it is modified, Matlab just spits back as an output.
[var1 a]=thisObject.DB.Execute(queryString,a)
See here
"The syntax shown here shows a server function being called by the MATLAB client. The function's return value is shown as retval. The function's output arguments (out1, out2, ...) follow this:
[retval out1 out2 ...] = handle.functionname(in1, in2, ...);
MATLAB makes use of the pass by reference capabilities in COM to implement this feature. Note that pass by reference is a COM feature. It is not available in MATLAB at this time."

Related

handing string to MATLAB function in Simulink

In my Simulink Model I have a MATLAB function, this_function, which uses as one parameter the name of the Simulink Model, modelname. The name is defined in an extra parameter file with all other parameters needed. Loading the parameter file loads modelname into the workspace. The problem is now, that this_function can't access modelname in the workspace and therefore the model doesn't run.
I tried to use modelname as a constant input source for this_function, which I used as a work-around previously, but Simulink doesn't accept chars/strings as signals. Furthermore does setting modelname to global not work as well.
Is there a way to keep modelname in the parameter file instead of writing it directly into this_function?
Simulink does not support strings. Like, anywhere. It really sucks and I don't know why this limitation exists - it seems like a pretty horrible design choice to me.
I've found the following workarounds for this limitation:
Dirty Casting
Let
function yourFun(num_param1, num_param2, ..., str_param);
be your MATLAB function inside the Simulink block, with str_param the parameter you want to be a string, and num_param[X] any other parameters. Then pass the string signal to the function like so:
yourFun(3, [4 5], ..., 'the_string'+0);
Note that '+0' at the end; that is shorthand for casting a string to an array of integers, corresponding to the ASCII codes of each character in the string. Then, inside the function, you could get the string back by doing the inverse:
model = char(str_param);
but usually that results in problems later on (strcmp not supported, upper/lower not supported, etc.). So, you could do string comparisons (and similar operations) in a similar fashion:
isequal(str_param, 'comparison'+0);
This has all the benefits of strings, without actually using strings.
Of course, the '+0' trick can be used inside constant blocks as well, model callbacks to convert workspace variables on preLoad, etc.
Note that support for variable size arrays must be enabled in the MATLAB function.
Fixed Option Set
Instead of passing in a string, you can pass a numeric scalar, which corresponds to a selection in a list of fixed, hardcoded options:
function yourFun(..., option)
...
switch (option)
case 1
model = 'model_idealised';
case 2
model = 'model_with_drag';
case 3
model = 'model_fullscale';
otherwise
error('Invalid option.');
end
...
end
Both alternatives are not ideal, both are contrived, and both are prone to error and/or have reusability and scalability problems. It's pretty hopeless.
Simulink should start supporting strings natively, I mean, come on.

Equivalent of R's str in Matlab? [duplicate]

I'd like to be able to view the structure of objects in Matlab/GNU Octave the same way as I do in R (using the str() function). Is there a function that does this? An example task would be returning nr rows and cols in matrix, but also all the arguments for a given function.
I'm aware that I could use both size() and help() (but not for function files) separately to get this information.
There are several useful functions for displaying some information about Matlab objects (I can't say anything about Octave compatibility), but I'm not sure they'll provide the same detail as R's str(). You can display all of the methods of a class with the methods function, e.g.:
methods('MException')
which returns
Methods for class MException:
addCause getReport ne throw
eq isequal rethrow throwAsCaller
Static methods:
last
The what function will return similar results. Or methods can be used on an object of a given class:
ME = MException('Test:test','Testing');
methods(ME)
Similarly, you can view the properties with properties and the events with events.

Problems with using delphi dta types with a C DLL

I am trying to use a .dll which has been written in C (although it wraps around a matlab .ddl)
The function I am trying to use is defined in C as:
__declspec(dllexport) int ss_scaling_subtraction(double* time, double** signals, double* amplitudes, int nSamples, int nChannels, double* intensities);
The .dll requires, amongst others, a 2 dimensional array - When I tried to use:
Array of array of double
In the declaration, the compiler gave an error so I defined my own data type:
T2DArray = Array of array of double;
I initialise the .dll function in a unit like so:
function ss_scaling_subtraction(const time: array of double; const signals: T2DArray; const amplituides : array of double; const nSamples: integer;const nChannels: integer; var intensities: array of double) : integer ; cdecl; external 'StirScanDLL.dll';
However, when called this function, I get an access violation from the .dll
Creating a new data type
T1DArray = array of double
and changing
Array of double
To
T1DArray
In the declaration seems to make things run but the result is still not correct.
I have read on here that it can be dangerous to pass delphi data types to .dll's coded in a different language so I thought this might be causing the issue.
But how do I NOT use a delphi data type when I HAVE to use it to properly declare the function in the first place?!
Extra Info, I have already opened the matlab runtime complier lib's and opened the entry point to the StirScanDLL.dll
The basic problem here is one of binary interop mismatch. Simply put, a pointer to an array is not the same thing at a binary level as a Delphi open array parameter. Whilst they both semantically represent an array, the binary representation differs.
The C function is declared as follows:
__declspec(dllexport) int ss_scaling_subtraction(
double* time,
double** signals,
double* amplitudes,
int nSamples,
int nChannels,
double* intensities
);
Declare your function like so in Delphi:
function ss_scaling_subtraction(
time: PDouble;
signals: PPDouble;
amplitudes: PDouble;
nSamples: Integer;
nChannels: Integer;
intensities: PDouble
): Integer; cdecl; external 'StirScanDLL.dll';
If you find that PPDouble is not declared, define it thus:
type
PPDouble = ^PDouble;
That is, pointer to pointer to double.
Now what remains is to call the functions. Declare your arrays in Delphi as dynamic arrays. Like this:
var
time, amplitudes, intensities: TArray<Double>;
signals: TArray<TArray<Double>>;
If you have an older pre-generics Delphi then declare some types:
type
TDoubleArray = array of Double;
T2DDoubleArray = array of TDoubleArray;
Then declare the variables with the appropriate types.
Next you need to allocate the arrays, and populate any that have data passing from caller to callee.
SetLength(time, nSamples); // I'm guessing here as to the length
SetLength(signals, nSamples, nChannels); // again, guessing
Finally it is time to call the function. Now it turns out that the good designers of Delphi arranged for dynamic arrays to be stored as pointers to the first element. That means that they are a simple cast away from being used as parameters.
retval := ss_scaling_subtraction(
PDouble(time),
PPDouble(signals),
PDouble(amplitudes),
nSamples,
nChannels,
PDouble(intensities)
);
Note that the casting of the dynamic arrays seen here does rely on an implementation detail. So, some people might argue that it would be better to use, for instance #time[0] and so on for the one dimensional arrays. And to create an array of PDouble for the amplitudes and copy over the addresses of the first elements of the inner arrays. Personally I am comfortable with relying on this implementation detail. It certainly makes the coding a lot simpler.
One final piece of advice. Interop can be tricky. It's easy to get wrong. When you get it wrong, the code compiles, but then dies horribly at runtime. With cryptic error messages. Leading to much head scratching.
So, start with the simplest possible interface. A function that receives scalar parameters. Say, receives an integer, and returns an integer. Prove that you can do that. Then move on to floating point scalars. Then one dimensional arrays. Finally two dimensional arrays. Each step along the way, build up the complexity. When you hit a problem you'll know that it is down to the most recently added parameter.
You've not taken that approach. You've gone straight for the kill and implemented everything in your first attempt. And when it fails, you've no idea where to look. Break a problem into small pieces, and build the more complex problem out of those smaller pieces.

get string of enum - matlab coder

I have an enum like this:
classdef(Enumeration) bla_type < int32
enumeration
bla_one(1)
bla_2(2)
end
end
I can get the 'string representation of an element' like this:
char(bla_type.bla_one)
=>
bla_one
Unfortunately, matlab coder does not like this. Are there any alternatives?
There's no elegant built-in way in Coder to do this; the enumerated type becomes a standard enum in C, and the enumeration function in MATLAB is unavailable in Coder. The simplest, but unpleasant, way to do it is to create a function with a switch statement with the manually populated string names. It's not nice, since now you have to maintain the names in two places.
However, one way that does work nicely is to use one of the more powerful features of Coder: coder.const.
The solution is to have a function that creates a table of the enumeration members and their values. This function itself cannot be compiled, but rather is called during compilation to build a lookup table in the resulting C code. We can use this lookup table in a Coder compatible function to get the data.
Imagine we have an enumerated type like this (in someenum.m):
classdef someenum < int32 %#codegen
enumeration
First_thing (0)
Second_thing (2)
Another_thing (3)
No_thing (4000)
end
end
We also then have the build-time function called 'buildsomeenum2name.m':
function [namearray, memberidx] = buildsomeenum2name
%BUILDSOMEENUM2NAME Compile-time creation of lookup table for someenum
% THIS FUNCTION IS NOT CODER COMPATIBLE, BUT IS CALLED DURING COMPILE
% TO CREATE A LOOKUP TABLE.
[members, names]=enumeration('someenum');
maxlen = 0;
for i=1:numel(names)
maxlen = max(maxlen, numel(names{i}));
end
namearray = char(zeros(numel(names), maxlen));
for i=1:numel(names)
namearray(i, 1:numel(names{i})) = names{i};
end
memberidx = int32(members); %#ok<NASGU>
end
When buildsomeenum2name is called in MATLAB, it creates an array of string names of all the members of the enumerated type and another vector list of their numeric values in the same order.
Here's the cool part. MATLAB Coder can evaluate functions at build time and turn them into constants. These constants become literals in the resulting C code, rather than actual code. Since the functions are evaluated at build time, the enumeration information is put into a nice table, therefore if we make a Coder-compatible lookup function, we can use it to convert the member types into a string. We'll call this function 'someenum2name.m':
function name = someenum2name(enum) %#codegen
%SOMEENUM2NAME Get the string name of an enumerated type
% The following line loads namearray and memberidx with constant arrays
coder.extrinsic('buildsomeenum2name');
[namearray, memberidx] = coder.const(#buildsomeenum2name);
% First find the index of the enumerated type in the memberidx vector
index = find(memberidx==int32(enum));
if isempty(index)
name = 'UNKNOWN';
return;
end
name = deblank(namearray(index,:));
end
This function uses the coder.const command to evaluate buildsomeenum2name at compile time and create the lookup tables. We have to instruct Coder not to try to compile buildsomeenum2name, so use the coder.extrinsic command to tell it to ignore the function. Then someenum2name can look up the index for the string and pull it out (deblank is used because the strings in the array have trailing 0's that need to be pulled out.) The function someenum2name can be called both within MATLAB and in Coder compiled code.
This method keeps everything in-sync, so if you ever add a new member to the enum or rearrange them, the coder.const function will make sure that the values are rebuilt in the output code so that someenum2name works.
At the command line, this looks like:
>> someenum2name(someenum.No_thing)
ans =
No_thing
Try [~,s]=enumeration('bla_type'). You get a cell array of strings containing the name of elements in s. So bla_one will be in s{1}. Don't know whether that is supported by MATLAB coder though.

getting multiple outputs from matlab to c#

I have written some functions in matlab.Now I need to get their outputs to C# .net form.I could success fully connect them through .Net Assembly and able to get output of a function which returns only one output to c#.Now I want to do it with a function which returns multiple outputs.Is there any particular way of doing this?????
thanks...
there are different signrature of the method available in the DLL, just use the proper one,
put the first input argument of the method as the number of outputs, then it will return an array of MWArray as outputs : (i.e below, 2 indicates that I expect to have an array of outputs with size 2)
MWArray[] res = MatlabDll.callMethod(2, x, y);
C# uses the Tuple Class for solving this issue.