From Friday, April 19th (11:00 PM CDT) through Saturday, April 20th (2:00 PM CDT), 2024, ni.com will undergo system upgrades that may result in temporary service interruption.

We appreciate your patience as we improve our online experience.

Example Code

Universal Cluster to C Struct with Endian-ness and Padding

Code and Documents

Attachment

Download All

Motivation: sometimes we need to call a C function that takes mixed data types in the form of a C Structure. While it is fairly easy to replicate the C Stuct as a LV Cluster it can be pretty hard to pass this to the C DLL due to the way LV and C understand data formats and byte packing. Sometimes the C developer has used the #pragma pack() directive to force a certain behavior and sometime this is left default and up to the processor ("natural alignment"?)

In the attached project are two main VIs: "Cluster to Struct" and "Struct to String".

The first takes pretty much any cluster and converts it to a byte array - in doing this it evaluates padding required based on the padding rules and the given #pragma directive.

Further, most (all?) C functions do not expect string size and array dimensions to be part of the data passed (expecting known size and initialize fields). This means size and dimension data need to be stripped from the byte stream and then "re-inserted" when converting back to LV data-types. Use the "Struct to String" function to convert back into a string that the magic LabVIEW-native function "unflatten from string" can understand.

There is an Example.vi to show some usage of these functions. Not included in the project is an actual DLL to consume/return the byte array. Some testing has been performed but if errors occur please leave a note in the comment section below. Also, don't forget to rate this example if you find it useful (or not).


CluterToStuct.png

Essentially, use these functions to get a byte array and then pass this directly into the C DLL using a Call Library Function Node.

In the CLFN parameter use:

Type: Array,

Data Type: Unsigned 8-bit Integer,

Array Format: Array Data Pointer,

Minimum Size: None.

Comments welcome!

20141114 - "v2" update: bug fixes in array handling and more complex examples provided

Example code from the Example Code Exchange in the NI Community is licensed with the MIT license.

Comments
Jason2010
Member
Member
on

Quite interesting example, could you please convert it to LV2012 SP1 version? Thanks.

djac91
Member
Member
on

good example. Thnaks for sharingSmiley Happy

-----------------------------------------------------------------------------------------------------------------------------
Waiting For the inner calling 🙂


Contributors