Unable to access RTTI for SmartMobileStudio - smart-mobile-studio

Trying to use Smart's RTTI as defined in this post, I was not able to let RTTI be emitted to the HTML.
When I define:
type
TBase = class
published
Field : Integer = 1;
end;
var base := new TBase;
PrintPropertiesForType(base);
Then, there is no RTTI available for this class.
In index.html, I have:
var $RTTI = [];
Meaning that there is no RTTI emitted.
This occurs for whatever Project Options I have set. (in short, the RTTI compilation option does not make any difference)
I’m using SMS 2.0.1.741.
I’m stuck with implementing a native SMS client for mORMot..

There seem to be a bug with this issue in the latest hotfix. I have reported the issue to the developer team and it should be fixed shortly. I noticed the exact same thing myself testing the RTTI methods on different versions of SMS.
An immediate solution is to just roll-back to version 2.0.0.723.
You can download that version here:
http://smartmobilestudio.com/download/v2_0_0_723/

I found out that it works in the main unit (TApplication) but not in other referenced units. So you can try that in the mean time

As an alternative to automatic persistence (since RTTI is not working in the latest hotfix and you have opted not to use RTTI for object mapping), it should be mentioned that Smart Pascal supports JavaScript structures. This will greatly simplify object storage. If you have ever used a Microsoft property-bag (com class) then this is more or less the same thing.
In JavaScript you would write:
var mbag = {};
mbag["test"] = {};
mbag["test"]["somevalue"] = 12;
mBag["text"] = "this is a string value";
Resulting in a memory structure like this:
Type
TMyBagContent = Record
bcTest = Record
bcSomeValue:Integer;
end;
bcText:String;
End;
In Delphi these kind of structures are implemented in SuperObject (I believe). RemObjects also have some support classes that mimic this. But thankfully Smart Pascal achieves this automatically by grace of targeting JavaScript directly.
So in Smart Pascal you would do the following to achieve the same results:
var mBag:Variant;
mBag:=TVariant.CreateObject;
mBag['test'] := TVariant.CreateObject;
mBag['test']['somevalue']:=12;
mBag['text']:='this is a string';
You can also save some time and use an assembly section:
var mBag:variant;
asm
#mbag = {};
#mbag["test"] = {};
#mbag["test"]["somevalue"] = 12;
#mbag["text"] = "this is a string value";
end;
Once you have populated your object's data, you then use JSON to serialize and make it portable:
var mObj: String;
asm
#mObj = JSON.stringify(#mbag);
end;
Creating reader/writer class for storage is very easy. Naturally automatic RTTI property mapping is better (and that should be fixed shortly), but for frameworks that does it manually - which does have some advantages over full automation - there are plenty of options for creative programmers such as yourself.
There is also speed to consider, and using a JavaScript object as a lookup table is very, very fast compared to a for/next recursive algorithm. Especially for large and complex data structures.
Looking forward to testing your creation :)

Related

Convert IVectorView to std::span

winrt::hstring is convertible to std::basic_string_view which comes in handy quite often. However, I am unable to do the same for IVectorView.
Looking at the interface of IVector, I imagine you would have to convert it back to the underlying implementation type so I tried
using impl_type = winrt::impl::vector_impl<float, std::vector<float>, winrt::impl::single_threaded_collection_base>;
winrt::Windows::Foundation::Collections::IVectorView vector_view = GetIVectorView();
auto& impl = *winrt::get_self<impl_type>(vector_view);
auto& container = impl.get_container();
which compiles but container.size() is 0 which is incorrect.
Edit:
vector_view was the result of the TensorFloat.GetAsVectorView Method. So I can solve my problem by using the TensorFloat.CreateReference Method to get a IMemoryBufferReference instead of a IVectorView.
However, I'd still like to know whether IVectorView can be converted to a std::span, if not why is this not allowed.
The IVector and IVectorView interfaces are specifically designed not to expose the underlying contiguous memory, probably to support cases where there is no underlying contiguous memory or the implementation language doesn't expose it as such (javascript??).
You probably could get back the implementation type in when you know cppwinrt provides the implementation, however I'm my case there is no possible way of knowing the implemention type. In any case, it's inadvisable to do this.
In my case it would have been better if TensorFloat.GetAsVectorView did not exist so I could find TensorFloat.CreateReference.
Also it would be nice if cppwinrt made themselves range-v3 compatible. But until the most advisable thing to do is just copy to a std::vector.

MATLAB and the use of global variables?

I am writing a tool for dicom images and spectroscopy and there is a lot of shared data I want to use between the functions I am making. I have GUI that I made and the different sliders and buttons use a lot of this shared data from the dicom files.
I have been using global variables to store information that all of these functions share. I have a lot of globals currently. I have been taught to avoid global variables if possible because of increasing coupling. Would it be better to read in the data from the dicom file in each function? This seems redundant. Would using MATLAB as object-oriented help?
I would recommend using application data structures.
Application data is essential data stored as a structure that is defined by your application and is typically attached to a GUI application or figure window.
To use application data (appdata) use the setappdata and getappdata functions. For example, assuming that you have a handle to your GUI stored as hGUI, the following adds a random matrix to your application data and then retrieves it later (lifted from MATLAB documentation)
% Save matrix for later
matrix = randn(35);
setappdata(hGUI, 'mydata', matrix);
% Do some stuff...
% Retrieve my matrix, this could be in a different file to `setappdata`
myMatrix = getappdata(hGUI, 'mydata');
You can store essentially arbitrary data in your application data, and you can store it and get it from any of your source files, as long as hGUI refers to your GUI application.
Since you mention you are working with a GUI and wanting to share data between the control callbacks, I would suggest designing your code using nested functions. The overall code would look something like this:
function dicomGUI
%# Initialize your GUI here, linking the control callbacks to the
%# nested functions below:
hLoad = uicontrol('Style', 'push', 'String', 'Load file', ...
'Callback', #load_file);
...
%# Initialize the data variables for the DICOM files here:
data = []; %# Shared among nested functions
...
%# Below are all the nested functions your controls will use:
function load_file(hSource, event)
data = ...; %# Load the data here
end
...
end
Not only does this let you put all your GUI code in one m-file, but it simplifies the control callbacks and makes it easy for them to share variables in the workspace of the parent function dicomGUI. An example of this approach, along with other suggestions for sharing data between GUI controls, can be found on this documentation page: Share Data Among a GUI's Callbacks.
As Chris mentions, this could become a very large m-file for a large and intricate GUI. To keep the file size down in such a case I would suggest making the body of each callback simply a call to a function in a separate file which accepts the shared data variables, performs whatever work is necessary, then returns the modified data to the same shared variables. For example:
function transform_callback(hSource, event)
%# Apply some transform to the data:
data = transform_data(data);
%# If the above changes the GUI (disabling controls, changing a
%# display, etc.), then those changes should be made here.
end
Globals as a rule are a bad thing. There are a couple of better ways typically, which include:
Reading in the data initially, and passing it to each function which needs it.
Reading it the data, and each function which needs it calls a function which returns it.
You might need to update the data package upon return somehow as well, depending on if you only use the data or if you change the data as well as using it.
Either one of these ideas should help your process. It makes your code much more readable, and less likely to make some kind of a mistake.
There is another possibility due to the object-oriented nature of MATLAB. You can define your own handle class and pass it in the initialization phase to each callback as an additional argument:
classdef Data<handle
properties (Access=public)
Val;
end
end
function SimpleGui
data = Data();
hLoad = uicontrol('Style', 'push', 'String', 'Push me', ...
'Callback', {#callback data});
data.Val = 5;
end
function callback(hSource, event, data)
data.Val = data.Val+1;
disp(data.Val);
end
Yet another option:
Also, regarding the guidata/appdata (as described by #Chris), it can be improved in the following way:
Create an encapsulating callback that always gets and sets guidata:
function CallbackWrapper(hObj,evt,func)
data = guidata(hObj);
data = func(hObj,evt,data);
guidata(hObj,data);
end
Now your callbacks should be defined in the following way (note the different signature):
function SimpleGui
hSave = uicontrol('Style', 'push', 'String', 'Push me', ...
'Callback', {#CallbackWrapper #myCallBack});
data.x = 1;
guidata(hSave,data);
end
function data = myCallBack(hObj,evt,data)
data.x = data.x + 1;
disp(data.x);
end
If you are using one of the later releases of MATLAB, you should take advantage of the OOPS (object oriented programming system).
You should adhere to software design principles and start by architecting a sound software design. You should do this before writing any code. I recommend using UML for software modeling.

C#'s 'dynamic' in F#

One example of using the DLR in C# is as follows:
dynamic dyn = new MyObject();
dyn.MyMethod(); //resolved at runtime
what would be the equivalent in F#?
Thanks.
The ? operator has similar expressive power to the dynamic keyword in C# (but it can be only used for reading of properties, method invocation and setting of properties).
There is no built-in implementation that would allow you to dynamically use properties or methods of a .NET class (via Reflection or DLR), but there are some fairly solid implementations from the community. This has been discussed in another SO question before.
There are also implementations of ? that allow you access some common data sources such as SQL databases. For example, this MSDN article includes a definition that allows you to write db?Query?Foo(1) to call a stored procedure named Foo.
For various other types (such as finding an element in XAML or accessing elements or attributes in XML document), the definition of ? is quite easy to write.
On the flip side, if you're trying to expose dynamic behavior to C# from F#, you can use DynamicAttribute[MSDN]. For example, declaring a dynamic property might look like
type HasDynamicProperty() =
[<Dynamic([|true|])>]
member this.DynamicObject : obj = ...
which is used from C# like
var hdp = new HasDynamicProperty();
dynamic dynObj = hdp.DynamicObject;
There's a package called FSharp.Interop.Dynamic and that will make it possible to do a call to a dynamic object using the ? operator.
F# has the ? operator which you use like so:
myVariable?SomePropertyThatIsNotDeclared
There is no dynamic keyword equivalent. Take a look at this article for how to use it https://weblogs.asp.net/podwysocki/using-and-abusing-the-f-dynamic-lookup-operator

std::unique_ptr and pointer-to-pointer

I've been using std::unique_ptr to store some COM resources, and provided a custom deleter function. However, many of the COM functions want pointer-to-pointer. Right now, I'm using the implementation detail of _Myptr, in my compiler. Is it going to break unique_ptr to be accessing this data member directly, or should I store a gajillion temporary pointers to construct unique_ptr rvalues from?
COM objects are reference-countable by their nature, so you shouldn't use anything except reference-counting smart pointers like ATL::CComPtr or _com_ptr_t even if it seems inappropriate for your usecase (I fully understand your concerns, I just think you assign too much weight to them). Both classes are designed to be used in all valid scenarios that arise when COM objects are used, including obtaining the pointer-to-pointer. Yes, that's a bit too much functionality, but if you don't expect any specific negative consequences you can't tolerate you should just use those classes - they are designed exactly for this purpose.
I've had to tackle the same problem not too long ago, and I came up with two different solutions:
The first was a simple wrapper that encapsulated a 'writeable' pointer and could be std::moved into my smart pointer. This is just a little more convenient that using the temp pointers you are mentioning, since you cannot define the type directly at the call-site.
Therefore, I didn't stick with that. So what I did was a Retrieve helper-function that would get the COM function and return my smart-pointer (and do all the temporary pointer stuff internally). Now this trivially works with free-functions that only have a single T** parameter. If you want to use this on something more complex, you can just pass in the call via std::bind and only leave the pointer-to-be-returned free.
I know that this is not directly what you're asking, but I think it's a neat solution to the problem you're having.
As a side note, I'd prefer boost's intrusive_ptr instead of std::unique_ptr, but that's a matter of taste, as always.
Edit: Here's some sample code that's transferred from my version using boost::intrusive_ptr (so it might not work out-of-the box with unique_ptr)
template <class T, class PtrType, class PtrDel>
HRESULT retrieve(T func, std::unique_ptr<PtrType, PtrDel>& ptr)
{
ElementType* raw_ptr=nullptr;
HRESULT result = func(&raw_ptr);
ptr.reset(raw_ptr);
return result;
}
For example, it can be used like this:
std::unique_ptr<IFileDialog, ComDeleter> FileDialog;
/*...*/
using std::bind;
using namespace std::placeholders;
std::unique_ptr<IShellItem, ComDeleter> ShellItem;
HRESULT status = retrieve(bind(&IFileDialog::GetResult, FileDialog, _1), ShellItem);
For bonus points, you can even let retrieve return the unique_ptr instead of taking it by reference. The functor that bind generates should have signature typedefs to derive the pointer type. You can then throw an exception if you get a bad HRESULT.
C++0x smart pointers have a portable way to get at the raw pointer container .get() or release it entirely with .release(). You could also always use &(*ptr) but that is less idiomatic.
If you want to use smart pointers to manage the lifetime of an object, but still need raw pointers to use a library which doesn't support smart pointers (including standard c library) you can use those functions to most conveniently get at the raw pointers.
Remember, you still need to keep the smart pointer around for the duration you want the object to live (so be aware of its lifetime).
Something like:
call_com_function( &my_uniq_ptr.get() ); // will work fine
return &my_localscope_uniq_ptr.get(); // will not
return &my_member_uniq_ptr.get(); // might, if *this will be around for the duration, etc..
Note: this is just a general answer to your question. How to best use COM is a separate issue and sharptooth may very well be correct.
Use a helper function like this.
template< class T >
T*& getPointerRef ( std::unique_ptr<T> & ptr )
{
struct Twin : public std::unique_ptr<T>::_Mybase {};
Twin * twin = (Twin*)( &ptr );
return twin->_Myptr;
}
check the implementation
int wmain ( int argc, wchar_t argv[] )
{
std::unique_ptr<char> charPtr ( new char[25] );
delete getPointerRef(charPtr);
getPointerRef(charPtr) = 0;
return charPtr.get() != 0;
}

Description format for an embedded structure

I have a C structure that allow users to configure options in an embedded system. Currently the GUI we use for this is custom written for every different version of this configuration structure. What I'd like for is to be able to describe the structure members in some format that can be read by the client configuration application, making it universal across all of our systems.
I've experimented with describing the structure in XML and having the client read the file; this works in most cases except those where some of the fields have inter-dependencies. So the format that I use needs to have a way to specify these; for instance, member A must always be less than or equal to half of member B.
Thanks in advance for your thoughts and suggestions.
EDIT:
After reading the first reply I realized that my question is indeed a little too vague, so here's another attempt:
The embedded system needs to have access to the data as a C struct, running any other language on the processor is not an option. Basically, all I need is a way to define metadata with the structure, this metadata will be downloaded onto flash along with firmware. The client configuration utility will then read the metadata file over RS-232, CAN etc. and populate a window (a tree-view) that the user can then use to edit options.
The XML file that I mentioned tinkering with was doing exactly that, it contained the structure member name, data type, number of elements etc. The location of the member within the XML file implicitly defined its position in the C struct. This file resides on flash and is read by the configuration program; the only thing lacking is a way to define dependencies between structure fields.
The code is generated automatically using MATLAB / Simulink so I do have access to a scripting language to help with the structure creation. For example, if I do end up using XML the structure will only be defined in the XML format and I'll use a script to create the C structure during code generation.
Hope this is clearer.
For the simple case where there is either no relationship or a relationship with a single other field, you could add two fields to the structure: the "other" field number and a pointer to a function that compares the two. Then you'd need to create functions that compared two values and return true or false depending upon whether or not the relationship is met. Well, guess you'd need to create two functions that tested the relationship and the inverse of the relationship (i.e. if field 1 needs to be greater than field 2, then field 2 needs to be less than or equal to field 1). If you need to place more than one restriction on the range, you can store a pointer to a list of function/field pairs.
An alternative is to create a validation function for every field and call it when the field is changed. Obviously this function could be as complex as you wanted but might require more hand coding.
In theory you could generate the validation functions for either of the above techniques from the XML description that you described.
I would have expected you to get some answers by now, but let me see what I can do.
Your question is a bit vague, but it sounds like you want one of
Code generation
An embedded extension language
A hand coded run-time mini language
Code Generation
You say that you are currently hand tooling the configuration code each time you change this. I'm willing to bet that this is a highly repetitive task, so there is no reason that you can't write program to do it for you. Your generator should consume some domain specific language and emit c code and header files which you subsequently build into you application. An example of what I'm talking about here would be GNU gengetopt. There is nothing wrong with the idea of using xml for the input language.
Advantages:
the resulting code can be both fast and compact
there is no need for an interpreter running on the target platform
Disadvantages:
you have to write the generator
changing things requires a recompile
Extension Language
Tcl, python and other languages work well in conjunction with c code, and will allow you to specify the configuration behavior in a dynamic language rather than mucking around with c typing and strings and and and...
Advantages:
dynamic language probably means the configuration code is simpler
change configuration options without recompiling
Disadvantages:
you need the dynamic language running on the target platform
Mini language
You could write your own embedded mini-language.
Advantages:
No need to recompile
Because you write it it will run on your target
Disadvantages:
You have to write it yourself
How much does the struct change from version to version? When I did this kind of thing I hardcoded it into the PC app, which then worked out what the packet meant from the firmware version - but the only changes were usually an extra field added onto the end every couple of months.
I suppose I would use something like the following if I wanted to go down the metadata route.
typedef struct
{
unsigned char field1;
unsigned short field2;
unsigned char a_string[4];
} data;
typedef struct
{
unsigned char name[16];
unsigned char type;
unsigned char min;
unsigned char max;
} field_info;
field_info fields[3];
void init_meta(void)
{
strcpy(fields[0].name, "field1");
fields[0].type = TYPE_UCHAR;
fields[0].min = 1;
fields[0].max = 250;
strcpy(fields[1].name, "field2");
fields[1].type = TYPE_USHORT;
fields[1].min = 0;
fields[1].max = 0xffff;
strcpy(fields[2].name, "a_string");
fields[2].type = TYPE_STRING;
fields[2].min = 0 // n/a
fields[2].max = 0 // n/a
}
void send_meta(void)
{
rs232_packet packet;
memcpy(packet.payload, fields, sizeof(fields));
packet.length = sizeof(fields);
send_packet(packet);
}