Professional Documents
Culture Documents
TM
Contents
Student Guide
A.
B.
C.
D.
E.
F.
Lesson 1
Review of Basics I Concepts
Introduction.................................................................................................................1-1
The Callback Function Model ....................................................................................1-2
Introduction to Messaging ..........................................................................................1-3
Messaging ...................................................................................................................1-4
Structure of Instrument Drivers ..................................................................................1-5
Accessing Instrument Drivers.....................................................................................1-6
Toolslib Instrument Drivers........................................................................................1-7
Summary Lesson 1......................................................................................................1-8
Lesson 2
User Interface Programming
Introduction.................................................................................................................2-1
Lesson 2 Project..........................................................................................................2-2
Exercise 2-1
User Interface Project .......................................................................2-4
Attributes ....................................................................................................................2-5
Exercise 2-2
Search ...............................................................................................2-7
Menus..........................................................................................................................2-11
Menu Editor ................................................................................................................2-12
Menu Callback Functions ...........................................................................................2-14
Menus: Programming Method ....................................................................................2-15
Exercise 2-3
Menus ...............................................................................................2-17
Canvas Control ...........................................................................................................2-24
Graphs versus Canvases..............................................................................................2-25
Using a Canvas ...........................................................................................................2-26
Useful Type Definitions for Canvases........................................................................2-27
Useful Functions for Canvases ...................................................................................2-28
Canvas Functions ........................................................................................................2-29
Exercise 2-4
Canvas Controls................................................................................2-31
Table Control ..............................................................................................................2-36
Table Control Components .........................................................................................2-37
Programming with the Table Control .........................................................................2-38
Exercise 2-5
Table Controls ..................................................................................2-41
iii
Contents
Lesson 3
Interapplication Communication and ActiveX Automation
Introduction.................................................................................................................3-1
ActiveX Technologies ................................................................................................3-2
Client-Server Relationship..........................................................................................3-3
Type Library ...............................................................................................................3-4
ActiveX Automation Client-Server Architecture .......................................................3-5
ActiveX Features in LabWindows/CVI......................................................................3-6
LabWindows/CVI as ActiveX Container ...................................................................3-7
LabWindows/CVI as Automation Client....................................................................3-8
LabWindows/CVI as Automation Server ...................................................................3-9
Exercise 3-1
Using ActiveX Objects.....................................................................3-11
ActiveX Automation...................................................................................................3-13
LabWindows/CVI as an Automation Client ...............................................................3-14
Creating Automation Clients ......................................................................................3-15
LabWindows/CVI ActiveX Controller Wizard ..........................................................3-16
Wizard-Generated Functions ......................................................................................3-17
ActiveX Functions ......................................................................................................3-17
Automation Data Types ..............................................................................................3-18
Other ActiveX Library Functions ...............................................................................3-19
Exercise 3-2
Using an ActiveX Server..................................................................3-21
Exercise 3-3
Creating an ActiveX Client Application ..........................................3-28
LabWindows/CVI as an Automation Server ..............................................................3-35
Creating ActiveX Servers ...........................................................................................3-36
Editing ActiveX Servers .............................................................................................3-37
Exercise 3-4
Running an ActiveX Server..............................................................3-39
DataSocket Technology ..............................................................................................3-40
LabWindows/CVI Basics II Course Manual
iv
ni.com
Contents
Lesson 4
Code Modularity and Compatibility
Introduction.................................................................................................................4-1
Modules ......................................................................................................................4-2
Dynamic Link Library (DLL).....................................................................................4-4
Creating DLLs ............................................................................................................4-6
Calling Conventions ...................................................................................................4-7
Using DLLs.................................................................................................................4-8
Exercise 4-1
Creating a DLL in LabWindows/CVI ..............................................4-10
Exercise 4-2
Using a DLL Created in LabWindows/CVI.....................................4-15
Debugging DLL Code ................................................................................................4-16
Exercise 4-3
Examining DLL Debugging Features ..............................................4-19
DLL Recommendations ..............................................................................................4-21
Compatibility with External Compilers ......................................................................4-22
Using LabWindows/CVI Libraries in External Compilers.........................................4-23
Other Issues with External Compilers ........................................................................4-27
Using the User Interface Library with External Compilers ........................................4-30
Exercise 4-4
Creating an Object File for Use in an
External Compiler (Optional)...........................................................4-33
Exercise 4-5
Creating a DLL for Use in an External Compiler (Optional)...........4-37
Summary Lesson 4......................................................................................................4-39
Contents
Lesson 5
Additional Topics
Introduction.................................................................................................................5-1
Multithreading Terms .................................................................................................5-2
Multithreaded Programs .............................................................................................5-3
Benefits of Multithreading..........................................................................................5-4
Multithreading in LabWindows/CVI..........................................................................5-5
Thread Pools ...............................................................................................................5-6
Thread Pool Example..................................................................................................5-7
Exercise 5-1
Multithreading in LabWindows/CVI ...............................................5-10
Thread Safe Queues ....................................................................................................5-12
Thread Safe Queue Example ......................................................................................5-13
Exercise 5-2
Using a Thread Safe Queue..............................................................5-15
Well-Behaved Applications ........................................................................................5-24
Platform Software Development Kit (SDK)...............................................................5-25
Benefits of Using SDK Functions ..............................................................................5-26
Additional Functions...................................................................................................5-27
I/O and Memory Space ...............................................................................................5-28
Memory Display Window ..........................................................................................5-29
Source Code Browser .................................................................................................5-30
Handling Executables in LabWindows/CVI...............................................................5-31
Error Handling ............................................................................................................5-32
Set Sleep Policy ..........................................................................................................5-33
Additional Functionality .............................................................................................5-34
Toolkits .......................................................................................................................5-35
Summary Lesson 5......................................................................................................5-38
LabWindows/CVI Publications ..................................................................................5-39
Continuing with National Instruments........................................................................5-40
Appendix A
Additional Information and Resources
Course Evaluation
vi
ni.com
Student Guide
Thank you for purchasing the LabWindows/CVI Basics II course kit.
This course manual and the accompanying software are used in the two-day,
hands-on LabWindows/CVI Basics II course.
You can apply the full purchase price of this course kit toward the
corresponding course registration fee if you register within 90 days of
purchasing the kit. Visit ni.com/training to register for a course and to
access course schedules, syllabi, and training center location information.
Certification Track
LabWindows CVI
Experience
LabWindows CVI
Basics I
LabWindows CVI
Basics II
Certified LabWindows
CVI Developer Exam
Instrument Driver
Development
B. Course Description
The LabWindows/CVI Basics II course is a follow-up to the
LabWindows/CVI Basics I course. This course is ideal for new and
intermediate users. After attending the course, you can design powerful
multithreaded applications that use Internet communication, DLLs, and
ActiveX. You will learn how to create powerful user interfaces using active
menus, canvas controls, and toolbars. You will be able to take full advantage
of the PC with your application by learning how to program a multithreaded
application. This course assumes that you have completed
LabWindows/CVI Basics I course or you are familiar with the
LabWindows/CVI environment and possess basic C programming skills.
vii
Student Guide
The course is divided into lessons, each covering a topic or a set of topics.
Each lesson consists of the following parts:
Description
Exercises
Solutions
viii
ni.com
Student Guide
E. Course Goals
This course presents the following topics:
ix
Student Guide
F. Course Conventions
The following conventions are used in this course manual:
<>
[]
The symbol leads you through nested menu items and dialog box options
to a final action. The sequence FilePage SetupOptions directs you to pull
down the File menu, select the Page Setup item, and select Options from
the last dialog box.
This icon denotes a tip, which alerts you to advisory information.
This icon denotes a note, which alerts you to important information.
bold
Bold text denotes items that you must select or click in the software, such as
menu items and dialog box options. Bold text also denotes parameter names,
buttons on the User Interface (*.uir), and sections and components of
dialog boxes. Window names and palette names are also denoted in bold.
italic
monospace
Text in this font denotes text or characters that you enter from the keyboard,
sections of code, programming examples, and syntax examples. This font
also is used for the proper names of disk drives, paths, directories, programs,
subprograms, subroutines, device names, functions, operations, variables,
filenames, and extensions.
monospace bold
Bold text in this font denotes the messages and responses that the computer
automatically prints to the screen. This font also emphasizes lines of code
that are different from the other examples.
monospace
italic
Italic text in this font denotes text that is a placeholder for a word or value
that you must supply.
ni.com
Introduction
In this lesson, you will learn about the concepts that are the foundation for building
LabWindows/CVI programs.
1-1
Lesson 1
1-2
ni.com
Lesson 1
Introduction to Messaging
A message queue is set up when the operating
system starts your application
As events occur, the operating system stores
different messages in the queue
Your application continuously checks the queue to
take action on the various messages
Introduction to Messaging
When discussing the general callback function mechanism internal structure, it is necessary to look
at the concept of operating system messaging. A common construct in modern operating systems
(Windows 2000/NT/9x included), a messaging scheme offers applications a consistent and
straightforward way to respond to modern graphical user interfaces and other types of actions.
In addition to other services provided to every application, the operating system (OS) manages a
message queue for the application. When the OS detects events such as a mouse movement, it
places well-defined messages in this queue. An application loops and polls to check for messages
in the queue. If messages exist, the application removes the messages and takes appropriate action.
In a LabWindows/CVI application, think of ProcessSystemEvents as the function that checks
the queue and takes appropriate action. As discussed in LabWindows/CVI Basics I,
RunUserInterface manages the core looping of your application and relies on the functionality
of ProcessSystemEvents.
ProcessSystemEvents examines the new message and determines how to handle it. In the case
of a user interface action, ProcessSystemEvents determines the appropriate control and calls
1-3
Lesson 1
Messaging
ProcessSystemEvents
CVICALLBACK function ()
switch(event)
{
case EVENT_LEFT_CLICK:
Left-mouse down
break;
Left-mouse up
case EVENT_COMMIT:
break;
}
Message queue
Messaging
The figure above illustrates the general message processing scheme. Consider the following
example:
A LabWindows/CVI application with a simple one-button panel is running. When the user
clicks and releases the left mouse button, the OS queues the appropriate messages.
ProcessSystemEvents, whether you call it directly or call it through RunUserInterface,
detects these messages and extracts them from the queue. Upon examining the messages,
ProcessSystemEvents determines that the user clicked and released the button on the
application. First, the function sends an EVENT_LEFT_CLICK to your buttons callback function.
Then, when that call returns, ProcessSystemEvents calls the function again with the
EVENT_COMMIT. ProcessSystemEvents does the message-handling work for you. For this
reason, it is important that you understand the callback function mechanism because you must
always first check the event passed into the function and determine what action to take. The
switch-case C language structure is the best way to do this.
Note User interface callback functions typically return 0. If the function returns a
nonzero number, any subsequent callbacks resulting from that particular event are not
called. This process is known as swallowing the event.
1-4
ni.com
Lesson 1
1-5
Lesson 1
Add the .fp file to the LabWindows/CVI Library menu. In the Workspace window, select
LibraryCustomize to add libraries.
Add the .fp file to the Instruments folder of the Library Tree. Right-click the Instruments
folder and select Load Instrument.
Add the .fp file to your project. Doing so causes LabWindows/CVI to load the instrument each
time it loads your project file.
Auto-load the .fp file from another instrument driver. You can auto-load a .fp file when you
have an instrument driver that relies on code in an external library. Rather than compiling that
library into your own instrument driver or forcing the instrument driver user also to load the
support library, you can configure one instrument driver to auto-load another. To configure
auto-loading, select InstrumentEdit, which opens the Edit Instrument dialog box. Click Edit
Function Tree to open the Function Tree Editor. Then select Edit.FP Auto-Load List and
list the .fp files for the instrument drivers you want to load when the current instrument driver
is loaded. The instrument driver from which to auto-load the .fp files must be loaded to
complete these steps.
Because the .fp file does not contain any code, you can add only the source and header
modules to your project and use them as if they were not associated with an instrument driver
at all. In this case, you lose the benefits of the function panels.
1-6
ni.com
Lesson 1
1-7
Lesson 1
Summary Lesson 1
Lesson 1 reviews and extends core LabWindows/CVI
concepts from the Basics I course.
Callback function programming model
Instrument drivers as user libraries
Toolslib instrument drivers
Summary Lesson 1
This lesson describes key programming concepts with the LabWindows/CVI libraries. Lesson 2
gives you hands-on experience developing programs with toolslib instrument drivers to
implement advanced user interface features.
1-8
ni.com
Lesson 1
Notes
1-9
Lesson 1
Notes
1-10
ni.com
Attributes
Menus
Intensity graphs
Canvases
Table controls
Tree controls
Custom controls
Toolbars
Introduction
With LabWindows/CVI user interface functions and features, you can build powerful, event-driven
GUIs quickly.
As you develop LabWindows/CVI applications, you add user interface controls to panels, edit their
properties, and then create the corresponding callback functions to handle user events that are
generated by operations on those controls.
You can enhance your applications with advanced user interface controls, custom controls, and
built-in user interface features that increase usability and flexibility for the end user.
This lesson focuses on user interface programming style and taking advantage of your own user
interface elements.
2-1
Lesson 2
Project
Lesson 2 Project
In this lesson, you will create a project that uses several LabWindows/CVI user interface (UI)
features. The project integrates menus, toolbars, canvas controls, multiple panels, intensity graphs,
table controls, and tree controls. You add each feature one at a time, so that you can see how each
benefits the overall application.
The final section in this lesson covers many of the custom control instrument drivers that ship with
LabWindows/CVI.
2-2
ni.com
Lesson 2
Exercise 2-1
OBJECTIVE
2-3
Lesson 2
Exercise 2-1
Objective:
Menus
Intensity graphs
Canvas controls
Table controls
Tree controls
Toolbars
3. Click the Quit button when you finish studying the application.
2-4
ni.com
Lesson 2
Attributes
All user interface objects have attributes such as color, visibility,
position, or size.
For example, this STOP button has the following attributes:
Color:
Red
Visibility: True
GetCtrlAttribute and SetCtrlAttribute retrieve and set control attribute
values.
Attributes
In LabWindows/CVI, every UI object has attributes such as color, visibility, position, and size.
Some objects have specific attributes. For example, a graph has attributes for grid lines and its
X and Y axes. You can set the attributes of objects in the User Interface Editor. You also can set the
attributes programmatically. Use the User Interface Library GetCtrlAttribute and
SetCtrlAttribute functions to change the appearance and functionality of UI objects.
2-5
Lesson 2
Exercise 2-2
OBJECTIVE
2-6
ni.com
Lesson 2
Exercise 2-2
Objective:
Search
Examine the following code for the SearchRoutine function that you will
create in this exercise. Complete the steps following the code to use
LabWindows/CVI to quickly develop the code for the SearchRoutine
function.
2-7
Lesson 2
Buffer
Starting Index
searchposition
Number of Bytes
Pattern
FindThis
Case Sensitive?
No
No
Result
result
2-8
ni.com
Lesson 2
6. Insert an If-Else statement to test if a result was found from the search
string. FindPattern returns 1 if the string is not found. Select Edit
Insert ConstructIf Else. In the If Else dialog box, enter
result >= 0 for the condition. Click OK to insert the construct.
7. FindPattern uses searchposition to determine where to start
searching for a particular text string. In order for FindPattern to
find multiple instances of the same search string, it is necessary to set
the value of searchposition equal to one character after the
FindPattern result. This allows FindPattern to search for the text
string after the current search instance. Enter the following code in the
if statement:
searchposition = result + 1;
mainPanel
Control ID
MAINPANEL_TEXTBOX
Control Attribute
Attribute Value
result
2-9
Lesson 2
Panel Handle
mainPanel
Control ID
MAINPANEL_TEXTBOX
Control Attribute
Attribute Value
strlen(FindThis)
9. Use SetActiveCtrl to make the text box the active control so that the
user can see the highlighted text. From the Library Tree, select User
Interface LibraryControls/Graphs/Strip ChartsGeneral
FunctionsSetActiveCtrl and complete the function panel for the
function call, as shown in the following table. After you finish, select
CodeInsert Function Call.
Panel Handle
mainPanel
Control ID
MAINPANEL_TEXTBOX
Message
12. Save and run the project. Test the application to confirm that the search
function works properly and highlights the appropriate string in the text
box when the search string is found.
2-10
ni.com
Lesson 2
Menus
Create menus in the User Interface Editor
You must load a menu onto a panel
Menus have callbacks similar to controls and panels
Menu
Menu
Item
Menu Bar
Submenu
Menus
In LabWindows/CVI Basics I, you learned how to create GUIs. Now, you will learn how to add
pull-down menus to your panels so that your program looks and feels like a modern application.
Menus are primarily for user input. You do not display information in a menu as you do in a
numeric indicator.
The following list describes important menu terms:
Menu barA menu bar is the entire menu associated with a panel. For example, the Source
window in LabWindows/CVI has a menu bar consisting of File, Edit, View, Build, and so on.
MenuA menu is one element of the menu bar. File is one menu, Edit is another.
Menu itemA menu item is an element from the pull-down menu. Open is an item of the File
menu.
Immediate Action MenuAn immediate action menu is a menu that has no menu items
placed beneath it. An exclamation point appears next to the immediate action menu name.
2-11
Lesson 2
Menu Editor
Menu bar prefix combined with constant name creates the MENU_FILE
Control ID
Name that
appears in menu
Menu Editor
You can program and identify menu bars and panels in a similar way. Remember that a panel has
a constant name. The Control ID of any control placed on that panel consists of this panel constant
name followed by the controls own constant name. For example, PNL_GRAPH is the Control ID of
a graph that has the constant name GRAPH and is placed on a panel that has the constant name PNL.
You use this Control ID when you need to refer to a specific control programmatically.
Menu bars also have constant names, and any menu or menu item placed on the menu bar inherits
that name. For example, if you add a File menu with the constant name FILE to a menu bar with
the constant name MENU, the File menu ID is MENU_FILE. If you add an Open menu item with the
constant name OPEN under the File menu, the Open menu item ID is MENU_FILE_OPEN. To create
menus in the User Interface Editor, select CreateMenu Bar.
Menu Editor Terms
Menu Bar Constant PrefixThe constant name associated with a menu bar. This prefix is
similar to the constant name given to a panel.
Constant NameThe unique name that identifies a menu or menu item on the menu bar. This
name is similar to the constant name given to a control on a panel.
Item NameThe text shown in the menu bar such as File, Edit, and so on. You can use this
text for a pull-down menu or a menu item.
Callback FunctionThe name of the function that executes when you select the menu item.
Modifier Key and Shortcut KeyThe hot key combination accesses the menu item. Using
this combination is equivalent to using the mouse to select the menu item.
2-12
ni.com
Lesson 2
The buttons on the right-hand side of the menu editor position the menu item in the menu hierarchy.
You can move a menu item up, down, right, or left in the menu hierarchy. For example, to create a
File menu with Open and Exit as two menu items, place File in the menu hierarchy and insert the
Open and Exit menu items into the menu. Then highlight the Open item and click the right-hand
Change Level button to position the Open item as a child item of File. Repeat this process with
the Exit menu item. You also can insert items below an item by clicking the Insert Child Item
button.
2-13
Lesson 2
menuBarThe handle of the menu bar that contains the item. Handles are returned from the
LoadMenuBar function. This is similar to LoadPanel.
menuItemThe specific control ID of the item selected. If several menu items use the same
callback function, use this parameter to determine which menu item was selected.
2-14
ni.com
Lesson 2
This function returns a handle to the menu bar that is used in subsequent calls to menu functions.
filenameThe absolute or relative pathname for the .uir file that contains the menu bar
resource.
menuBarResourceIDThe defined constant assigned to the menu bar in the User Interface
Editor.
2. You can create menus and menu bars programmatically using NewMenuBar, NewMenu, and
NewMenuItem. You also can retrieve and change the attributes of a menu bar, such as font
style, with the GetMenuBarAttribute and SetMenuBarAttribute functions.
2-15
Lesson 2
Exercise 2-3
OBJECTIVE
2-16
ni.com
Lesson 2
Exercise 2-3
Objective:
Menus
2. Use this dialog box to create the menu bar. To add entries to the menu,
fill in the list boxes.
a. Create the File menu with the following entries.
MENU
Constant Name
FILE
2-17
Lesson 2
Item Name
File
Callback Function
Leave blank
b. Click the Insert Child Item button to create the Open menu item
under the File menu. Use the following entries in the Edit Menu Bar
dialog box.
Menu Bar Constant Prefix
MENU
Constant Name
OPEN
Item Name
Open
Callback Function
OpenText
Modifier Key
MenuKey (Ctrl)
Shortcut Key
c. Click the Insert Item button to create the Save menu with the
following entries.
Menu Bar Constant Prefix
MENU
Constant Name
SAVE
Item Name
Save
Callback Function
SaveText
Modifier Key
MenuKey (Ctrl)
Shortcut Key
d. Click the Insert Item button to create the Exit menu item with the
following entries.
MENU
Constant Name
EXIT
Item Name
Exit
Callback Function
ExitProgram
Modifier Key
None
Shortcut Key
No Shortcut Key
2-18
ni.com
Lesson 2
e. Click the Insert Item button to create the Search menu with the
following entries.
Menu Bar Constant Prefix
MENU
Constant Name
SEARCH
Item Name
Search
Callback Function
Leave Blank
Modifier Key
None
Shortcut Key
No Shortcut Key
MENU
Constant Name
FIND
Item Name
Find
Callback Function
FindString
Modifier Key
None
Shortcut Key
No Shortcut Key
g. Click the Insert Item button to create the Case Sensitivity menu
item with the following entries.
MENU
Constant Name
CASE
Item Name
Case Sensitivity
2-19
Lesson 2
Callback Function
SetCaseSensitivity
Modifier Key
None
Shortcut Key
No Shortcut Key
Ensure that the Edit Menu Bar dialog box is similar to the one shown
in the following figure. After you verify that your dialog box
matches the one shown, click OK. Save uiproject.uir.
OpenText
SaveText
2-20
ni.com
Lesson 2
ExitProgram
FindString
SetCaseSensitivity
mainPanel
Filename
"uiproject.uir"
MENU
hMenu
6. Fill in the code for the menu callback functions as shown in the
following figure.
2-21
Lesson 2
2-22
ni.com
Lesson 2
7. Save and run the project. Verify that menu functions and the command
buttons work properly.
2-23
Lesson 2
Canvas Control
Canvas Control
The canvas control is an arbitrary drawing surface for drawing text, shapes, and bitmap images. The
major advantages of using a canvas over a graph are speed and flexibility. The canvas control
functions consist of low-level functions for bitmap manipulation and for drawing lines, text, and
points.
With graphs, you can plot static, numerical data. If you want to display items that require more
capabilities than a graph, you can take advantage of a canvas control.
2-24
ni.com
Lesson 2
2-25
Lesson 2
Using a Canvas
Use a canvas for the following tasks:
To draw objects using low-level primitives, such as pie charts
and Smith charts
To use and manipulate bitmaps (animation)
To avoid the overhead associated with graphs
Using a Canvas
When deciding between the various display options available to you, choose the UI object that
provides the most built-in features for your purpose. Use graphs and strip chart controls to graph
data in standard ways and use canvas controls for specialty purposes.
One thing to remember is that graphs have a wide range of capabilities. Study the examples that
ship with LabWindows/CVI to determine the possibilities of both graphs and canvas controls.
When programming with canvas controls, remember that canvases have attributes you can change
programmatically, such as the draw policy, overlapped policy, and coordinate system. You also can
use the bitmap functions in close association with the canvas functions.
2-26
ni.com
Lesson 2
typedef struct {
int x;
int y;
} Point;
2-27
Lesson 2
To understand these functions, consider the CanvasDrawLineTo function. This function draws a
line between the current pen position and the specified end point and sets the pen position to the
end point. The function draws the line with the current pen attributes including color, mode, width,
and style. The end point is defined by a structure of type Point, which specifies the x and y
coordinates.
CanvasDrawLineTo (hPanel, PANEL_CANVAS, MakePoint (100, 200));
This function draws a line from the current pen position to x = 100, y = 200, where the top left
corner of a canvas control is x = 0, y = 0.
2-28
ni.com
Lesson 2
Canvas Functions
Located in the Library Tree under
User Interface Library
Controls/ Graphs/Strip Charts
Canvas
Canvas Functions
The canvas control functions are located in the Library Tree under User Interface Library
Controls/Graphs/Strip ChartsCanvas. You can create a wide variety of shapes with the
CanvasDraw functions. To draw a point, use CanvasDrawPoint. Other options include line,
rectangle, oval, arc, polygon, text, and bitmap.
Use CanvasSet/GetPenPosition to control an imaginary pen within the canvas control. You
can fully control the pen attributes and location. You can determine whether the pen touches the
user interface, the pen thickness and color, and so on.
Because you cannot delete individual traces on a canvas control, you must either retrace or clear
everything within a specified area. Use CanvasClear to retrace or clear the area. To update any
changes to the canvas control immediately, call CanvasUpdate.
If you make several canvas function calls in a row, nest the calls between
CanvasStartBatchDraw and CanvasEndBatchDraw because there is an associated system
overhead for each canvas function call that these functions eliminate.
2-29
Lesson 2
Exercise 2-4
OBJECTIVE
2-30
ni.com
Lesson 2
Exercise 2-4
Objective:
Canvas Controls
SHOWCANVAS
Callback Function
ShowCanvasPanel
Label
Show __Canvas
After you create the button, the main panel should be similar to the
following figure.
2-31
Lesson 2
CNVSPANEL
Panel Title
In the following steps, you modify the newly created panel so that it
contains a canvas control, timer control, and Close button. After you
finish the steps, your canvas should be similar to the following figure.
2-32
ni.com
Lesson 2
Filename
"uiproject.uir"
Panel Resource ID
CNVSPANEL
Panel Handle
canvasPanel
2-33
Lesson 2
6. The DrawCanvas function detects when the user clicks the canvas to
start drawing. The drawing continues as long as the user continues to
hold down the left mouse button. Use the following code for this
function.
DrawCanvas starts the timer so that if the user holds down the left
mouse button, the timer callback function draws a line between the
current pen position and a specified end point. This function also obtains
the position of the mouse within the canvas and sets the canvas pen to
that position.
7. TimerTick draws a continuous line while a user holds down the left
mouse button. The code for this function is as follows.
TimerTick obtains the position of the mouse and checks the value of
the variable lButtonDown. If lButtonDown is set to true from the
DrawCanvas function, TimerTick draws a line from the previous pen
position to the current mouse position. If lButtonDown is set to false,
TimerTick turns the timer off.
2-34
ni.com
Lesson 2
2-35
Lesson 2
Table Control
Table Control
One of the more advanced controls in LabWindows/CVI is the table control. The table control is a
powerful and flexible tool for storing and operating on tabular data. With the table control, you can
display arrays, perform spreadsheet operations, and sort data.
The table control has built-in functionality to select and edit data, which is similar to the
functionality of a spreadsheet program. Data can be selected by row, column, or individual cell. The
table control also provides built-in searching and sorting functions and provides the ability to jump
to certain cells automatically. The table control can contain several data types including strings,
numbers, and even pictures.
2-36
ni.com
Lesson 2
Context Menu
Cell
Row
Column
2-37
Lesson 2
SetTableRowAttribute
SetTableColumnAttribute
SetTableCellAttribute
2-38
ni.com
Lesson 2
When a mouse event occurs on a table control, the cell can be found with
the following code:
Point mouse, cell;
mouse = MakePoint (eventdata2, eventdata1);
GetTableCellFromPoint (panel, TABLE,
mouse, &cell);
2-39
Lesson 2
Exercise 2-5
OBJECTIVE
2-40
ni.com
Lesson 2
Exercise 2-5
Objective:
Table Controls
SHOWTABLE
Callback Function
ShowTablePanel
Label
Show __Table
After you create the button, the main panel should be similar to the
following figure.
2-41
Lesson 2
7. Make sure that CodeSet Target File is set to table.c. Before you
generate the callback function for the Show Table button, select
CodePreferencesDefault Control Events and select only
EVENT_COMMIT. Click OK. Right-click the Show Table button
and select Generate Control Callback. This command generates the
callback function for the button in the table.c file.
8. Select CreatePanel to create a new panel. Double-click the panel and
specify TABLEPANEL as the panel constant name and Table Control
Panel as the panel title.
9. Select CreateLists & TablesTable to add a table control to the new
panel. Double-click the table control to open the Edit Table dialog box.
In this dialog box, you can create rows and columns, initialize cells, and
format the table.
a. Enter Test Results as the label of the table.
b. Disable the Row Labels Visible checkbox.
c. Set the Scroll Bars option to Vertical Scroll Bar.
d. Click the Insert Column After button to add the first column to
the table.
e. Click the Edit Column button. Enable the Use Label Text
checkbox and enter Test ID in the Label textbox as shown in the
following figure.
2-42
ni.com
Lesson 2
f. Click the Edit Default Cell Values button to change the Type to
Numeric and the Data Type to int.
g. Click OK to close the Edit Default Cell Values dialog box.
h. Click OK again to close the Edit Column dialog box and return to
the Edit Table dialog box.
10. Click Insert Column After button to add new column. Repeat the
process in step 9 parts d through h with the values in the following
tables.
Column 2
Width
130
Label Text
Date/Time
Cell Type
String
int
Column 3
Width
50
Label Text
Meas. 1
Cell Type
Numeric
double
Column 4
Width
50
Label Text
Meas. 2
Cell Type
Numeric
double
2-43
Lesson 2
Confirm that your table has four columns and the Edit Table dialog box
is similar to the one shown in the following figure.
11. Close the Edit Table dialog box by clicking OK and size the table to
show all four columns completely.
12. Add a command button to the panel with the constant name RUNTEST,
the callback function RunTest, and the label __Run Test.
13. Add another command button to the panel with the constant name
CLOSE, the callback function CloseTablePanel, and the label
__Close.
14. For each new button, right-click the button and select Generate Control
Callback to generate the callback functions in table.c.
The completed panel should be similar to the following figure.
15. Save and close the uiproject.uir file.
2-44
ni.com
Lesson 2
The table.c now contains three empty callback functions that require
modifications
16. Place your cursor in the EVENT_COMMIT case in the ShowTablePanel
callback function. You must call LoadPanel to load the panel. From the
Library Tree, select User Interface LibraryPanelsLoadPanel and
complete the function panel as shown in the following table. When you
finish, select CodeInsert Function Call.
Parent Panel Handle
Filename
"uiproject.uir"
Panel Resource ID
TABLEPANEL
Panel Handle
tablePanel
2-45
Lesson 2
18. The CloseTablePanel callback function hides the table panel with
RemovePopup. From the Library Tree, select User Interface Library
Pop-up PanelsRemovePopup and then insert the function call.
19. To remove the panel from memory select User Interface Library
PanelsDiscardPanel from the Library Tree. Enter tablePanel as
PanelHandle and then insert the function call.
20. Save table.c and run the project. Verify that the table panel works
properly and the Run Test button adds a row of data to the table. Also,
right-click the table to try the built-in pop-up context functions.
2-46
ni.com
Lesson 2
Tree Control
Tree Control
Another advanced control in LabWindows/CVI is the tree control. The tree control is a powerful
and flexible tool for storing and operating on data that has a parent-child relationship, such as files
in a directory. With the tree control, you can easily search and sort data stored in the tree.
The tree control uses all of the same functionality as a list box control. This means that you can use
list box functions on tree controls. You also can use functions that are specific to tree controls.
These functions are located in the Library Tree under User Interface Library
Controls/Graphs/Strip ChartsList/Tree (Label/Value) ControlsTrees.
The tree control uses a row index to identify items in the tree. The first item in the tree has the row
index of zero. The second item in the tree has the row index of one, and so on. The level of the tree
item depends on whether the item is a parent, a child, or a sibling. An item that has one or more
child items associated with it is called a parent item. A child item always is indented from its parent.
Items that are at the same level are considered sibling items. An item that has no parent is a root
item and is always at the top of the hierarchy. You can expand or collapse a parent node to display
or hide its child items.
Select CreateLists & TablesTree to create a tree control in the User Interface Editor. Use the
Edit Tree dialog box to add items to the tree and to edit these items.
2-47
Lesson 2
2-48
ni.com
Lesson 2
Exercise 2-6
OBJECTIVE
2-49
Lesson 2
Exercise 2-6
Objective:
Tree Controls
2. Add a command button to the main panel that launches the tree panel.
Double-click the command button to open the Edit Command Button
dialog box. Complete the dialog box as shown in the following table.
Constant Name
SHOWTREE
Callback Function
ShowTreePanel
Label
Show __Tree
After you create the button, the main panel should be similar to the
following figure.
2-50
ni.com
Lesson 2
4. Create a new panel. Give the panel the constant name TREEPANEL and
the panel title Tree Control Panel.
Populate the newly created panel with a tree control and command
buttons. Create a panel similar to the following figure.
5. Add a tree control to the new panel. Right-click the panel and select
Lists & TablesTree. Double-click the tree control to open the Edit
Tree dialog box.
a. Enter Tree Test as the label of the table.
b. Assign the tree control the constant name TREE.
6. Add the Insert Child command button to the panel. Assign the button
the constant name INSERTCHILD, the callback function InsertChild,
and the label Insert __Child.
7. Add the Insert Sibling command button to the panel. Assign the button
the constant name INSERTSIBLING, the callback function
InsertSibling, and the label Insert __Sibling.
8. Add the Delete Item command button to the panel. Assign the button the
constant name DELETEITEM, the callback function DeleteItem, and
the label __Delete Item.
9. Add the Close command button to the panel. Assign the button the
constant name CLOSE, the callback function CloseTreePanel, and the
label C__lose.
10. Right-click each button and select Generate Control Callback.
11. Access the untitled .c file through the Window menu. Save the new
.c file as tree.c. Add the file to the project by selecting FileAdd
tree.c to Project.
12. Save the uiproject.uir file.
2-51
Lesson 2
Part B: Code
The tree.c now contains five empty callback functions that require the
following modifications.
1. Use LoadPanel to modify the ShowTreePanel function to launch the
TREEPANEL.
a. Complete the function panel as shown in the following table.
Parent Panel Handle
Filename
"uiproject.uir"
Panel Resource ID
TREEPANEL
PanelHandle
treePanel
treePanel
Control ID
TREEPANEL_TREE
Relation
Child
Relative Index
index
Position
Last
Item Label
"Child"
Tag Base
2-52
ni.com
Lesson 2
Tag
Item Value
index
This function inserts an item as a descendent of the item before it. If the
item is the first item to be inserted into the tree, the function ignores the
Relation parameter and always inserts the item as a parent item.
5. Enter index = index + 1; to increment the value of index by one
after the child item is inserted into the tree.
6. In the InsertSibling callback function, call the InsertTreeItem
function as you did in step 4. Complete the function panel as shown in
the following table and insert the function call.
Panel Handle
treePanel
Control ID
TREEPANEL_TREE
Relation
Sibling
Relative Index
index
Position
Last
Item Label
"Sibling"
Tag Base
Tag
Item Value
index
This function inserts an item at the same level as the last item placed into
the tree. If the inserted item is the first to be inserted into the tree, the
function ignores the Relation parameter and inserts the item as a parent
item.
7. Enter index = index + 1; to increment the value of index by one
after the sibling item is inserted into the tree.
8. In the DeleteItem callback function, you want to implement code that
deletes only an item that has been selected by the user. Only items that
do not have any descendents can be deleted. This step shows how you
also can use the list functions to control the tree control.
2-53
Lesson 2
treePanel
Control ID
TREEPANEL_TREE
Active Index
&active
2-54
ni.com
Lesson 2
treePanel
Control ID
TREEPANEL_TREE
Item Index
active
Number of Descendents
&descendents
treePanel
Control ID
TREEPANEL_TREE
Item Index
active
Number of Items
e. When the item has been deleted, subtract one from the variable
index, since an item has been removed from the tree. To do this,
enter index = index - 1; in the if statement. Remember that
the variable index indicates where the item needs to be placed into
the tree when a child or sibling is inserted into the tree.
9. The CloseTreePanel callback function hides and removes the panel
from memory with RemovePopup and DiscardPanel as in the
previous exercise.
10. Save tree.c and run the project. Verify that the tree functions correctly.
Later in the course you will create a tree control that displays a directory
listing of the files on your computer.
2-55
Lesson 2
Intensity Graphs
2-56
ni.com
Lesson 2
Remember that the z-array uses [y][x] values rather than [x][y].
2-57
Lesson 2
2-58
ni.com
Lesson 2
2-59
Lesson 2
Exercise 2-7
OBJECTIVE
2-60
ni.com
Lesson 2
Exercise 2-7
Objective:
2. Open the intgraph.c file and add it to the project. This file contains a
utility function called GenerateData, which generates the data for the
intensity graph. Examine this function and how the data is generated.
Leave the file open in the Source window.
3. Open the uiproject.uir file.
a. Add a command button to the main panel that launches the tree
panel. Double-click the command button to open the Edit Command
Button dialog box. Complete the dialog box as shown in the
following table.
Constant Name
SHOWGRAPH
Callback Function
ShowGraphPanel
Label
Show __Graph
After you create the button, the main panel should be similar to the
following figure.
2-61
Lesson 2
a. Add a graph control to the panel with the constant name INTGRAPH
and a label of Intensity Graph.
b. Add a command button to the panel with the constant name PLOT,
the callback function PlotData, and the label __Plot.
c. Add a command button to the panel with the constant name CLOSE,
the callback function CloseGraphPanel, and the label __Close.
d. Right-click each button and select Generate Control Callback to
generate the callback functions in intgraph.c.
e. Save and close the uiproject.uir file.
5. Write the three new callback functions.
a. Write the ShowGraphPanel callback function to display the
GRAPHPANEL panel. Use LoadPanel to load the panel and use
InstallPopup to display the panel. Use the variable graphPanel
as the Panel Handle for the Intensity Graph Panel. Finally, insert the
function call.
b. Write the PlotData callback function to call GenerateData and
then plot the data with the PlotIntensity function.
c. Enter GenerateData(); in the PlotData callback function.
d. Select User Interface LibraryControls/Graphs/Strip Charts
Graphs and Strip ChartsGraph Plotting and Deleting
PlotIntensity and complete the function panel as shown in the
2-62
ni.com
Lesson 2
graphPanel
Control ID
GRAPHPANEL_INTGRAPH
Z Array
dataPoints
Number of X Points
XPOINTS
Number of Y Points
YPOINTS
Z Data Type
double precision
colors
HiColor
HICOLOR
Number of Colors
COLORS
Interp Colors?
Interp Pixels
6. (Challenge) Write your own data generation function that creates the data
and the Color Map Array for the PlotIntensity function.
2-63
Lesson 2
2-64
ni.com
Lesson 2
2-65
Lesson 2
2-66
ni.com
Lesson 2
2-67
Lesson 2
2-68
ni.com
Lesson 2
2-69
Lesson 2
Exercise 2-8
OBJECTIVE
2-70
ni.com
Lesson 2
Exercise 2-8
Objective:
To use a predefined custom control to quickly add powerful user interface features
to an application.
This project shows how you can use a LabWindows/CVI custom control in
an application. In the project, you will use the File Browser custom control
to add a File Manager to an application.
1. Create a new project in LabWindows/CVI and save the project as
C:\Exercises\CVI Basics II\Lesson 2\
CustomControl.prj.
2-71
Lesson 2
2-72
ni.com
Lesson 2
2-73
Lesson 2
This function creates a new toolbar on the specified panel at the position specified by top and left.
menuBar is the menu handle associated with the toolbar, if any. newToolbar is the toolbar handle
for the new toolbar (passed by reference).
The Toolbar_Display function displays the toolbar. If the toolbars parent panel is not visible,
the toolbar does not appear until the parent is displayed.
To set a particular toolbar item value, use Toolbar_SetItemVal.
The following function adds items to the toolbar:
int Toolbar_InsertItem (ToolbarType toolbar, int position, int itemType,
int active, const char *description, int callbackType, int
menuItem, CtrlCallbackPtr controlCallbackFunction, void
*callbackData, const char *imageFile);
positionSpecifies where in the toolbar the button is placed, relative to other buttons.
2-74
ni.com
Lesson 2
itemTypeThe control type of the item, which can be a command button, toggle button,
separator, or ring.
descriptionA string describing the button. This string appears when the user holds the
mouse cursor over the given button.
callbackTypeSpecifies the type of callback function associated with the toolbar item like
control callback, menu callback, or no callback.
menuItemThe Control ID for the menu item that the button is associated with if
callbackType is set to menu callback. Otherwise, this parameter is ignored.
imageFileThe filename, including any path, of the image for the button.
2-75
Lesson 2
Exercise 2-9
OBJECTIVE
2-76
ni.com
Lesson 2
Exercise 2-9
Objective:
Toolbars
mainPanel
Menu Bar
hMenu
Title
"Search Toolbar"
Top
Left
Yes
Conform to System
Yes
New Toolbar
&hToolbar
Note Remember that hMenu was declared in Exercise 2-3. The toolbar functions can
use the existing callback functions that are defined with the menu for toolbar callbacks.
This is the reason for specifying the Menu Bar parameter when you create a new toolbar.
5. Add the toolbar items. The toolbar shows five buttons and
two separators as shown in the following figure.
2-77
Lesson 2
hToolbar
Position
Description
Active
Yes
Item Type
Command Button
Callback Type
Menu Callback
Menu Item
MENU_FILE_OPEN
Callback Data
Image File
"buttons\\open.pcx"
Description
Menu Item
MENU_FILE_SAVE
Image File
"buttons\\save.pcx"
First Separator
Position
Description
""
2-78
ni.com
Lesson 2
Item Type
Separator
Callback Type
No Callback
Menu Item
Image File
""
Find button
Position
Description
"Find"
Item Type
Command Button
Callback Type
Menu Callback
Menu Item
MENU_SEARCH_FIND
Image File
"buttons\\find.pcx"
Description
"Case Sensitivity"
Item Type
Toggle Button
Menu Item
MENU_SEARCH_CASE
Image File
"buttons\\case.bmp"
Second Separator
Position
Description
""
Item Type
Separator
Callback Type
No Callback
Menu Item
Image File
""
2-79
Lesson 2
Description
"Terminate Program"
Item Type
Command Button
Callback Type
Menu Callback
Menu Item
MENU_FILE_EXIT
Image File
"buttons\\stop.pcx"
8. Save and run the program. When LabWindows/CVI prompts you to add
the necessary include file at the top of the file, select Yes. Verify that the
toolbar is present and functions properly.
2-80
ni.com
Lesson 2
2-81
Lesson 2
Summary Lesson 2
Lesson 2 describes several user interface features that enhance standard
LabWindows/CVI GUI application development.
User interface features
Attributes
Menus
Canvas controls
Table controls
Tree controls
Intensity graphs
User-defined custom controls
Predefined custom controls
Remember that you can create your own custom controls.
Summary Lesson 2
After completing the exercises in this lesson, you are now familiar with a wide assortment of user
interface featuresattribute programming, menus, custom controls, and other user interface
objects. The purpose of the lesson is not only to help you learn about these user interface features
but also to help you become more familiar with LabWindows/CVI user interface programming
style. The LabWindows/CVI programming methodology is consistent, which helps you move from
user interface programming to instrumentation-based programming quickly.
2-82
ni.com
Lesson 2
Notes
2-83
Lesson 2
Notes
2-84
ni.com
A.
B.
C.
D.
Introduction
In interapplication communication, concurrently running applications communicate with each
other. Communication involves sharing data or higher-level tasks such as initiating actions in other
applications, sending events, and so on. In this lesson, you will learn about popular technologies
used to implement interapplication communication, including ActiveX Automation, TCP, and
DataSocket.
You also will learn how to use ActiveX Automation to extend the functionality of an application
by reusing code from a separate application that implements the desired functionality. This chapter
describes in brief Microsofts ActiveX technology.
Complete description of the ActiveX technology is beyond the scope of this course.
3-1
Lesson 3
ActiveX Technologies
ActiveX is a set of technologies that uses the
Microsoft Component Object Model (COM)
ActiveX technologies include
ActiveX controls in containers
ActiveX documents
ActiveX Automation
ActiveX Technologies
ActiveX technologies are a diverse set of technologies based on the Microsoft Component Object
Model (COM). The COM standard allows developers to create code and applications from many
different languages and build a defined interface to that code, making the code easily accessible to
other applications. An application can access another applications functionality through standard
interfaces.
The following list presents common ActiveX technologies:
ActiveX ControlsA control is an object that resides on a panel to accept input from the user
and to display information. ActiveX controls are components external to LabWindows/CVI,
which can be used in the same way as built-in LabWindows/CVI controls. ActiveX controls
vary in the functionality they provide. For example, an ActiveX control might store and
manipulate different types of data for word processing and report generation, for mathematical
calculations, or to access the internet. An application that houses an ActiveX control is called
the control container. The control container communicates with the control through methods
and properties. Thus, you can use Interactive objects, such as the calendar control, in
containers, such as Web browser.
3-2
ni.com
Lesson 3
Application
ActiveX Client
Component
uses
Client-Server Relationship
The application and the component have a client-server relationship. The application acts as a
client that uses the component services.
3-3
Lesson 3
Type Library
To create and access objects, automation clients need information about a server objects,
properties, and methods. Often, properties have data types, and methods return values and accept
parameters. The documentation of the server application contains extensive information about the
exposed objects, methods, and properties.
A list of exposed objects is provided in the application type library. A type library contains
specifications for all objects, methods, or properties exposed by an automation server. The type
library file usually has a .tlb filename extension.
When LabWindows/CVI acts as an ActiveX client, it uses information in the servers type library
to generate wrapper code that can be used to control the server. This wrapper code is organized as
a LabWindows/CVI instrument driver.
Interfaces
A COM interface is a group of related functions that forms the means of communication between
a client and a server.
3-4
ni.com
Lesson 3
Registry
Server A
Object 1
Server A
Step 3. instantiates Object 2
Step 2. interfaces with
Type Lib 2
Server B
Object
Step 3. instantiates
3-5
Lesson 3
ActiveX
Control
Automation
ActiveX
Server
(LabWindows/CVI)
Containment
(component controls)
ActiveX
Container
(Visual C++,
LabVIEW,
LabWindows/CVI)
3-6
ni.com
Lesson 3
LabWindows/CVI as
ActiveX Container
3-7
Lesson 3
3-8
ni.com
Lesson 3
3-9
Lesson 3
Exercise 3-1
OBJECTIVE
3-10
ni.com
Lesson 3
Exercise 3-1
Objective:
3-11
Lesson 3
3-12
ni.com
Lesson 3
ActiveX Automation
With ActiveX Automation, you can
Create applications that expose objects (automation
servers)
Create and control objects exposed in an automation
server application from another application (automation
clients)
ActiveX Automation
In ActiveX Automation, one application acts as the server, and the other application acts as a client.
The server exposes methods (actions) and properties (data) that a client can control and change.
For example, a spreadsheet application can be an automation server. An automation server might
expose objects, such as charts, ranges of cells, and so on, with methods to get and set these objects
properties. An automation client creates and controls objects exposed by the server application. For
example, a LabWindows/CVI program can launch Excel and open existing spreadsheets.
A class defines the type of properties and methods contained in an object. An ActiveX Automation
object is an instance of a class that exposes properties, methods, and events to ActiveX clients. An
automation object can have both methods and properties. For example, the methods of a Windows
object are actions, such as restore, minimize, and maximize, which you can perform using a
Windows control menu. The properties, such as height and width, describe the appearance of the
window.
3-13
Lesson 3
Dispatches
action and sets
properties
Gets properties
Automation Server
Type Library
3-14
ni.com
Lesson 3
3-15
Lesson 3
3-16
ni.com
Lesson 3
Wizard-Generated Functions
The instrument functions that the wizard creates contain calls to the functions in the
LabWindows/CVI ActiveX Library with appropriate arguments based on the information in the
type library of the automation server. For each top-level object, the wizard generates the necessary
functionsNew to create a new object, Open to open an object from a file, and Active to get a
handle to an existing object. The other objects are created by calling the methods of top-level
objects. At least one top-level object must be initially created/referenced in the client object. Use
the GetProperty, SetProperty, and SetPropertyByRef functions to get/set the server
properties. To create the client application, use the functions that the wizard generates in
combination with other LabWindows/CVI functions, especially those in the LabWindows/CVI
ActiveX Library.
ActiveX Functions
ActiveX Automation uses specially defined data types to handle data so that the data is compatible
with different programming environments. These data types are different from the ANSI C data
types. The LabWindows/CVI ActiveX Library provides functions to convert between the two kinds
of data types. The ActiveX Library also contains functions to handle the error information, if any,
returned by the automation server. The ActiveX Library contains low-level functions that you can
use instead of the wizard-generated functions or for special circumstances.
3-17
Lesson 3
VARIANTCan contain any other automation data type. Basically, a VARIANT is a union of all
BSTREquivalent to the C string, but a BSTR contains the number of characters in the string,
along with the characters themselves.
When using the ActiveX Library functions or the wizard-generated functions, you might need to
send/receive data in one of the preceding data types. This action requires you to handle these data
types and convert between these data types and C data types. You can use functions in the
LabWindows/CVI ActiveX Library to perform these conversions. The library has VARIANT-related
functions, SAFEARRAY-related functions, and BSTR-related functions.
For example, to convert a C string to a BSTR, call the CA_CStringToBSTR function as follows:
status = CA_CStringToBSTR (cStr, &bStr);
3-18
ni.com
Lesson 3
Low-level functions
Creating, getting, and loading objects
Calling methods and properties
3-19
Lesson 3
Exercise 3-2
OBJECTIVE
3-20
ni.com
Lesson 3
Exercise 3-2
Objective:
You can load an ActiveX control on the panel by right-clicking the panel and
selecting ActiveX. Then, select the ActiveX object from the Select ActiveX Object
dialog box and click OK.
Note
3-21
Lesson 3
PLAY
WHICHPLAYER
QUIT
playMovie
whichPlayer
quit
Hot
Hot
Hot
__Play Movie
__Which Player?
__Quit
You can use EditCopy and Paste to create the second and third buttons. Resize
a button by dragging its corner.
Note
3-22
ni.com
Lesson 3
panelHandle
PANEL_MEDIAPLAYER
3-23
Lesson 3
Panel Handle
Object Handle
panelHandle
&playerHandle
g. Clicking the Play Movie button prompts the user for an MPEG file
to be played in the Windows Media Player. The following
instructions show you how to add the code for the playMovie
callback function. The final playMovie callback function appears
as the following code.
The first function asks the user for a path to a file that will be
displayed in the Windows Media Player. Place your cursor inside the
playmovie callback function. From the Library Tree, select User
Interface LibraryPop-up PanelsFile/Directory Popups
FileSelectPopup. Complete the function panel as shown in the
following table and insert the function call.
3-24
ni.com
Lesson 3
Default Directory
Default File Spec
File Type List
Title
Button Label
Restrict Directory?
Restrict Extension?
Allow Cancel?
Allow Make Directory?
Path Name
Selection Status
load
no
no
yes
no
*.mpg
Select a MPEG
movie
path
playerHandle
NULL
path
h. Pressing the Which Player? button opens the About dialog box for
the Windows Media Player. The following instructions show you
how to add the code for the whichPlayer callback function.
The final whichPlayer callback function appears in the following
code.
3-25
Lesson 3
playerHandle
NULL
i. Clicking the Quit button discards the ActiveX object handle and
closes the application. Place your cursor inside the quit callback
function. From the Library Tree, select ActiveX LibraryResource
ManagementDiscardObjHandle to open the
CA_DiscardObjHandle function. Pass playerHandle to
the function.
j. Save and run the program. If prompted to add necessary include
statements to the top of the file, select Yes.
Note Newer versions of Windows Media Player may have different ActiveX methods
and properties.
3-26
ni.com
Lesson 3
Exercise 3-3
OBJECTIVE
3-27
Lesson 3
Exercise 3-3
Objective:
3-28
ni.com
Lesson 3
3-29
Lesson 3
3-30
ni.com
Lesson 3
a. Open the IE.c. Place your cursor in the Launch callback function.
b. Use InternetExplorerIWebBrowser2 to create a new Internet
Explorer browser object and obtain a handle to the object. Select
InstrumentsMicrosoft Internet ControlsIWebBrowser2New
InternetExplorerIWebBrowser2 from the Library Tree. Complete
the function panel as shown in the following table and insert the
function call.
Server
NULL
Support Multithreading
Locale
Reserved
Object Handle
LOCALE_NEUTRAL
0
&IEHandle
Object Handle
Error Info
IEHandle
Property ID
Property Type
Value
Visible
CAVT_BOOL
&error
VTRUE
3-31
Lesson 3
a. The first function asks the user for a path to a file to display in the
Web browser. Place your cursor in the Load callback function.
Select User Interface LibraryPop-up PanelsFile/Directory
PopupsFileSelectPopup from the Library Tree. Complete the
function panel as shown in the following table and insert the function
call.
Default Directory
Default File Spec
File Type List
Title
Button Label
Restrict Directory?
Restrict Extension?
Allow Cancel?
Allow Make Directory?
Path Name
""
"*.html"
""
"Select a Web Page"
load
No
No
Yes
No
path
Selection Status
3-32
ni.com
Lesson 3
&pathToVariant
Value
path
IEHandle
&error
pathToVariant
CA_DEFAULT_VAL
CA_DEFAULT_VAL
CA_DEFAULT_VAL
CA_DEFAULT_VAL
3-33
Lesson 3
Tip
Set IEHandle as a parameter for the Object Handle for steps 7 and 8.
7. Clicking the Close button closes and exits the browser application
without quitting the program.
a. Use the SHDocVw_IWebBrowser2Quit function, located in
InstrumentsMicrosoft Internet ControlsIWebBrowser2
IWebBrowser2Quit, to create this functionality.
b. It is very important to discard the object handle using the
CA_DiscardObjHandle function. You can access this function by
selecting ActiveX LibraryResource Management
DiscardObjHandle from the Library Tree. After you discard the
object handle, set IEHandle to 0.
8. Clicking the Quit button closes the program. If the browser application
is still running, close the application and discard the handle before
quitting the program. Include an if condition by selecting EditInsert
ConstructIf. Insert IEHandle!=0 in the Condition field of the If
dialog box.
.
Tip You can determine if the browser is still running by checking if IEHandle is not
set to 0. Remember that it is necessary to explicitly set IEHandle to 0 when the handle
has been discarded.
3-34
ni.com
Lesson 3
3-35
Lesson 3
3-36
ni.com
Lesson 3
3-37
Lesson 3
Exercise 3-4
OBJECTIVE
3-38
ni.com
Lesson 3
Exercise 3-4
Objective:
7. Click the Launch Server button to launch the server and enable the
Server Visibility option to see the server.
8. Manipulate the controls on the server application to see the server
functionality. Quit and close the server client when you finish.
Note simpleEXE.prj creates and registers an ActiveX server with the name
simpleEXE. This server can be called from any ActiveX client application, which can
be created with LabVIEW, Microsoft Visual Basic, Visual C++, and other compatible
compilers.
3-39
Lesson 3
DataSocket Technology
DataSocket Technology
Many instrumentation solutions involve a single local application for acquisition, logging, analysis,
and presentation. However, because of the rise in popularity of the Internet and company Intranets
and the need to monitor and control your data acquisition remotely, you often need to exchange live
data with other applications on different computers around the world. DataSocket simplifies live
data exchange between different applications on one computer or between computers connected
through a network.
A variety of different technologies, including TCP/IP and Dynamic Data Exchange (DDE), exist
today to share data between applications, but most of these tools are not targeted for live data
transfer to multiple clients. With TCP/IP, you must convert your data into an unstructured stream
of bytes in the broadcasting application and then parse the stream of bytes back into its original
format in subscribing applications. DataSocket, however, simplifies live data transfer. DataSocket
implements an easy-to-use, high-performance programming interface designed specifically to
share and publish live data in measurement and automation applications. In addition, DataSocket
features interapplication connectivity, rich data types, and security to make sharing data easy.
3-40
ni.com
Lesson 3
DataSocket Features
Live data transfer
Multiple clients
One high-level API for different source types
Avoids the burden of parsing
DataSocket Server manages networking
URL to specify connection
DataSocket Features
DataSocket is a single, unified, end-user Application Programming Interface (API) for connecting
to data from a number of sourceslocal files, files on FTP or Web servers, and data items on OPC
servers. To specify data locations, a DataSocket application uses a familiar networking standard,
the URL. Just as a Web browser uses a URL to connect to a Web page, a DataSocket application
uses a URL to connect to data. By using an industry-standard URL, you can quickly bring data into
or share data from your DataSocket applications. In addition, the DataSocket Transfer Protocol
connects a DataSocket application to live data by specifying a connection to a DataSocket Server.
The DataSocket Server, a lightweight, stand-alone component, manages most of the networking
tasks for you.
With the DataSocket Server programs using DataSocket, you can broadcast live measurement data
at high rates across the Internet to multiple remote clients concurrently. These client applications
use DataSocket to subscribe to the live measurement data. Because the DataSocket Server is a
stand-alone component, it simplifies network (TCP/IP) programming by automatically managing
connections to clients and automatically converting your measurement data to and from the stream
of bytes sent across the network. You do not need to write the parsing code. The DataSocket Server
can run on any machine on your network, which improves performance and provides security by
isolating the Web connections from your acquisition application.
3-41
Lesson 3
Data attributes
Transfer data properties
Can be easily configured/modified
Avoids user parsing
Interapplication connectivity
Security
Use DataSocket Server Manager to manage security privileges
3-42
ni.com
Lesson 3
DataSocket API
Main functions
DS_Open
DS_OpenEx
DS_DiscardObjHandle
DS_GetDataType
DS_GetDataValue
DS_Update
DS_SelectURL
DS_FreeMemory
DS_GetLibraryErrorString
Attribute functions
Status functions
Local Server Control function
DS_ControlLocalServer
DataSocket API
The DataSocket API contains the following functions:
Main functionsFunctions that open and discard handles to connections, get/set data values,
browse and select URLs, free resources, and update the connection. These are the functions you
need for most applications.
Attribute functionsFunctions that you use to work with data attributes. Use these functions
when you associate attributes, such as time-stamping data, information about physical units,
and so on.
Status functionsFunctions that provide status information about the DataSocket connection.
Polling Queue functionsFunctions that you use to get and set properties of DataSocket
polling queues. Currently, only the DataSocket Transfer Protocol (DSTP) supports polling.
3-43
Lesson 3
3-44
ni.com
Lesson 3
3-45
Lesson 3
Exercise 3-5
OBJECTIVE
3-46
ni.com
Lesson 3
Exercise 3-5
Objective:
dstp://localhost/value
DSConst_WriteAutoUpdate
NULL
NULL
Event Model
DSConst_Asynchronous
&dsHandle
3-47
Lesson 3
panelHandle
Control ID
Value
PANEL_VALUE
&value
dsHandle
double
&value
0
0
3-48
ni.com
Lesson 3
dstp://localhost/value
DSConst_ReadAutoUpdate
DataSocketEvent
NULL
Event Model
DSConst_Asynchronous
&dsHandle
At the bottom of the file, create the function shown in the following
figure. You will complete the code for this function later in this exercise.
3-49
Lesson 3
DS Handle
Type
Value
Size
Dimension 1
Dimension 2
dsHandle
double
&value
sizeof(double)
NULL
NULL
panelHandle
PANEL_VALUE
value
3-50
ni.com
Lesson 3
DataSocket Binding
Codeless DataSocket communication
Available with:
Numeric controls
Text box controls
Strip charts
Graphs
Tables
String controls
DataSocket Binding
LabWindows/CVI allows you to quickly publish and subscribe data on a DataSocket Server
without having to write any code. Using this feature, you can easily transfer data between
applications and platforms. DataSocket Binding is available with numeric controls, text box
controls, string controls, strip charts, graphs, and tables. To enable DataSocket Binding,
double-click the control and click the DataSocket Binding button in the Edit Control dialog box.
In the DataSocket Binding dialog box you can enable the binding, specify the location of the data,
and specify whether the control is a data publisher or subscriber.
3-51
Lesson 3
Exercise 3-6
OBJECTIVE
3-52
ni.com
Lesson 3
Exercise 3-6
Objective:
To create a DataSocket Writer and Reader application that uses DataSocket Binding.
a. Double-click the panel and enter DSWPANEL for the Constant Name
and DataSocket Writer for the Panel Title. Click OK.
b. Add a dial to the panel by right-clicking in the panel and selecting
NumericDial.
c. Double-click the dial to open the Edit Numeric Dial dialog box and
enter Data to Write as the Label.
d. Click the DataSocket Binding button. Select the Enable Data
Binding checkbox and complete the dialog box as shown in the
following table.
Server
Connection Type
dstp://localhost/data
Write
e. Click OK when done. Then click OK again to exit the Edit Numeric
Dial dialog box.
3-53
Lesson 3
a. Double-click the panel and enter DSRPANEL for the Constant Name
and DataSocket Reader for the Panel Title. Click OK when
done.
3-54
ni.com
Lesson 3
dstp://localhost/data
Read
f. Click OK when done. Then click OK again to exit the Edit Strip
Chart dialog box.
g. Add a command button to the panel. Double-click the command
button to open the Edit Command Button dialog box. Make the
constant name of the control QUIT, the callback function quit, and
the label __Quit. Then click OK.
5. Save the user interface as DSBReader.uir.
6. Select FileAdd DSBReader.uir to Project.
7. Select CodeGenerateAll Code.
8. In the Generate All Code dialog box, select Add to Current Project in
the Target Files section. Select quit in the Select QuitUserInterface
Callbacks section. Click OK to generate the code.
9. Create a release executable of this project and save it as
DSBReader.exe. To create the release executable, select Build
ConfigurationRelease and select BuildTarget TypeExecutable.
Select BuildCreate Release Executable.
Part C: Test
1. Run the DataSocket server if it is not running.
2. Run the DSBWriter.exe application and the DSBReader.exe
application.
3. Rotate the dial on the DataSocket Writer panel. Notice that the strip
chart plots the value of the dial when the dial value changes.
3-55
Lesson 3
3-56
ni.com
Lesson 3
OBJECTIVE
3-57
Lesson 3
Exercise 3-7
Objective:
To use the Convert CVI .FP File utility in LabVIEW to convert a LabWindows/CVI
instrument driver for use in LabVIEW.
Note This Exercise will work if LabVIEW Interface Generator for LabWindows/CVI
1.1 is installed on your computer. This installer is located in the C:\Exercises\CVI
Basics II\Lesson 3 directory. This installer creates LabVIEW VIs from instrument
drivers. You must have the following software installed before you can install and use the
LabVIEW Interface Generator for LabWindows/CVI Instrument Drivers.
Windows 2000/XP
3-58
ni.com
Lesson 3
12. Select all the files in the Select the files to generate during the conversion
process panel and click Next until you reach Accept or skip help string
replacement and deletion panel. Click the Accept All and click Next.
This completes the conversion.
3-59
Lesson 3
13. Clicking the View the Report and View VI Tree buttons displays the
report and the generated VI. When completed, click the Done button.
14. LabVIEW generates all the VIs and saves them in the destination
directory you specified in the conversion process. The default directory
is \National Instruments\LabVIEW 8.0\instr.lib\Devsim.
LabVIEW also puts the icons associated with these VIs in the
Instr.lib section of the Functions palette. You can access these VIs
by right-clicking a block diagram window and selecting Instrument
I/OInstrument DriverDevsim.
15. Open one of the generated VIs and study it. The VI uses a Call Library
Function to call the appropriate function in the Devsim_32.dll. The
following figure is the block diagram of DevSim Initialize.VI
generated by LabVIEW Interface Generator.
3-60
ni.com
Lesson 3
Perform an operation
on the VI
Refer to the wizard-generated function panel and the LabVIEW Help files for a comprehensive
discussion of each of the other methods and properties.
3-61
Lesson 3
OBJECTIVE
3-62
ni.com
Lesson 3
Exercise 3-8
Objective:
3-63
Lesson 3
3-64
ni.com
Lesson 3
Object Handle
LabviewHandle
Error Info
VI Path
Password
Resv For Call
Options
Return Value
NULL
pathName
VFALSE
0
&labviewVI
6. When the user clicks the Run Add button, add.vi runs, the sum is
calculated in LabVIEW and displayed in the sum control. The add.vi
has two inputs, num1 and num2, and one output, sum. add.vi adds
num1 and num2 and returns the value to sum.
a. In order to set the inputs num1 and num2 in add.vi, call the
VirtualInstrSetControlValue method. Place your cursor
after the comment. /* Set the values for the different
inputs on the VI */ in the AddRunCB callback function. From
the Library Tree, select InstrumentsLabVIEW 8.0 Type
LibraryVirtualInstrumentVirtualInstrSetControlValue and
complete the function panel as shown in the following table to set the
value of num1.
Object Handle
Error Info
Control Name
Value
labviewVI
NULL
num1
myValue1
following parameters.
3-65
Lesson 3
Object Handle
labviewVI
Error Info
Control Name
Value
NULL
num2
myValue2
labviewVI
NULL
VTRUE
labviewVI
Error Info
Control Name
Return Value
NULL
sum
&returnedValue
&returnedValue
&sum
3-66
ni.com
Lesson 3
f. Update the sum control on the panel with SetCtrlVal. From the
Library Tree, select LibrariesUser Interface Library
Controls/Graphs/Strip ChartsGeneral FunctionSetCtrlVal
and complete the function panel as shown in the following table to
set the value of num1.
Panel Handle
Control ID
Value
panelHandle
PANEL_SUM
sum
7. When the user clicks the Call Add button, add.vi is called as a subVI.
The VirtualInstrCall method in the VirtualInstrument class is
invoked. This function has arguments for the control values so you do
not need the VirtualInstrSetControlValue and
VirtualInstrGetControlValue methods. The code for the
function has already been written for you. Study how the function calls
the VI like a C function call, where the parameters are passed by calling
the function.
8. The Unload VI button discards add.vi, and the EXIT
LabVIEW button exits LabVIEW. This action occurs with the
DiscardObjHandle function in the ActiveX Library. Unload VI
discards the VI handle, and EXIT LabVIEW discards the LabVIEW
handle. The Quit button quits the program. The code has already been
written to discard the VI and exit the program.
9. Run the program. Ensure that the correct sum returns when the VI runs,
as well as when the VI is called as a subVI.
3-67
Lesson 3
155.247.207.70
TCP network
3-68
ni.com
Lesson 3
Client
Initiates and controls
the conversation
TCP-IP
3-69
Lesson 3
3-70
ni.com
Lesson 3
xTypeNumber that identifies a specific event for the client or server. The following table lists
the TCP transaction types that can trigger a callback function.
xType
Server Client
When?
TCP_CONNECT
TCP_DISCONNECT
TCP_DATAREADY
3-71
Lesson 3
RegisterTCPServer
ConnectToTCPServer
ServerTCPWrite
ServerTCPRead
UnregisterTCPServer
UnregisterTCPServer
ClientTCPWrite
ClientTCPRead
DisconnectFromTCPServer
Client Functions
existing server.
Both
3-72
ni.com
Lesson 3
ServerTCPRead/ClientTCPRead
TCP Event Manager
Server/Client
Sends Data
TCP_DATAREADY
Server/Client
Disconnects
TCP_DISCONNECT
Client Connects
TCP_CONNECT
ServerTCPRead/ClientTCPRead
The events that a TCP callback function recognizes are shown in the figure above. The following
code shows a typical TCP callback function.
int TCPcallback (int handle, int xType, int errCode, void *callbackData)
{
switch (xType) {
case TCP_DATAREADY:
/* handle incoming data.
use Server/ClientTCPRead*/
break;
case TCP_DISCONNECT:
/* notify user that the conversation
partner has disconnected */
break;
case TCP_CONNECT:
/* server only. notify user that a client
has connected */
break;
}
}
3-73
Lesson 3
Exercise 3-9
OBJECTIVE
3-74
ni.com
Lesson 3
Exercise 3-9
Objective:
2. Run the server executable. Enter an unused port number and select a data
source. If the data source is GPIB, enter the GPIB address of the device
simulator (most likely 2).
Run the client executable. Click the Connect to Server button. Enter the
IP address and port number of the server in the respective fields. When
connected, the client shows the IP address and the port number in the
Connected to field. After the client connects to the server, the Request
Data button is enabled. Select a waveform type and then click the
3-75
Lesson 3
Advanced button. After the server gathers the data and sends it to the
client, the client automatically plots the waveform to the screen.
3. When you are done, quit the programs by clicking the Quit button.
The RequestData callback executes when the user clicks the Request
Data button. This function then reads the Waveform Select ring control
and formats a command string using the Fmt function, which is similar
to the ANSI C sprintf function. This command string is passed to
ClientTCPWrite along with the conversation handle, the number of
bytes, and a timeout.
3-76
ni.com
Lesson 3
The Quit function disconnects the client from the server with
DisconnectFromTCPServer and exits the user interface.
Press <F2> to move to the main function. When the program starts, it
prompts the user to enter the port address for the server to use. Then the
program executes RegisterTCPServer and specifies this port address
and the server callback function. There is no need to give an IP address,
because RegisterTCPServer identifies the IP address from the
Windows environment.
The last tagged function is Quit. In this callback, the server executes
an UnregisterTCPServer to unregister itself and exit the user
interface.
3-77
Lesson 3
Summary Lesson 3
ActiveX Automation and how to create ActiveX
clients in LabWindows/CVI
DataSocket technology, which provides a high-level
API to transfer data between different entities
Connecting to LabVIEW from LabWindows/CVI
using ActiveX
TCP and using TCP to control applications on the
network
Summary Lesson 3
In this lesson, you learned how LabWindows/CVI can interact with other applications using a
variety of methods.
ActiveX AutomationWith ActiveX Automation, you can use the methods and control the
properties of objects from other applications instead of recreating the functionality within
LabWindows/CVI.
DataSocketWith DataSocket, you can transfer live data from application to application(s)
regardless of the underlying data protocol.
TCPWith TCP, you can communicate between simultaneously running applications over a
network connection.
Each technology has a client-server architecture, and it is important that you understand the role
each one plays.
If you want to combine the power of graphical programming with C-based programming, you can
connect to LabVIEW through VI Server or convert LabWindows/CVI instrument drivers to
LabVIEW instrument drivers.
3-78
ni.com
Lesson 3
Notes
3-79
Lesson 3
Notes
3-80
ni.com
Introduction
When you develop large applications, consider designing them in a modular fashion. This means
that the application is partitioned into distinct modules. Each module possesses a logical grouping
of functions or achieves a specific functionality.
This modularity serves several purposes:
Modules can be source files, object files, static libraries, and dynamic link libraries (DLLs). Each
of these modules has different advantages and disadvantages. In this lesson, you will learn how to
create and use DLLs. Later in this lesson, we will discuss issues regarding porting code between
development environments.
4-1
Lesson 4
Modules
What are modules?
Types of modules
Modules
In C programming, the instructions to the computer reside in one or more files. The files that
actually contain code and are translated into machine instructions are called modules. Normally,
a program consists of more than one module. The following list describes the different kinds of
modules.
Source files.c files are text files that contain code in C grammar. The compiler compiles
this code into an object file and generates executable code out of the source file.
Object files.obj files, which are in binary format, are usually generated from source files
and are linked with other object and library files to generate the final program. The object files
contain tables with symbolic information about the functions and variables in the original
source code.
Static Library files.lib files, which are in binary format, are usually a collection of object
files. These files are used to organize a set of related functions into one module, which allows
for easy access from various other source and object modules. For example, the analysis
functions in LabWindows/CVI are organized in the analysis.lib module. These files are
linked in by the LabWindows/CVI linker to create the executable program.
Dynamic Link Libraries (DLLs).dll files are binary files, but they differ from object and
static library files in that they are fully resolved, meaning that the functions inside a DLL do
not depend on any other module. The code inside a DLL is linked in only when the program is
executed, not when the program is created.
How does the compiler know, when creating the program, which functions to call in the DLL and
where the functions are located inside the DLL? This information is provided by a file known as
the import library for that DLL. The import library, .lib, is a static library file and contains code
4-2
ni.com
Lesson 4
to reliably link to the functions in the DLL at run time. As the name suggests, import libraries
contain code to import code from DLLs.
Header (.h) files are not modules. Header files do not contain code that can be translated into
machine instructions. Header files provide prototyping information for functions defined in
modules. The information inside a header file is always reproduced in source modules by the
#include directive.
4-3
Lesson 4
4-4
ni.com
Lesson 4
The disadvantage of using DLLs is that the complexity of application development increases. Your
application is no longer simply packaged into a single executable file. The executable requires the
DLLs it calls to be present on the target system. Because the code inside DLLs does not depend on
any other modules, you can port code from one environment to another in the form of DLLs, rather
than in the form of object and library files.
4-5
Lesson 4
Creating DLLs
Relationship between DLL, import library, and header files
Target Settings dialog box
DLL Files
.dll
Function
Definitions
DLL Header
Prototypes of
Exported Functions
Creating DLLs
Creating a DLL is not any more difficult than creating a static C library or an object module.
Although DLLs are linked at run time whereas static libraries are linked when the build occurs,
their source code can be identical. For example, you can take an existing source file for a static
library, change the BuildTarget Type setting in LabWindows/CVI to Dynamic Link Library,
and build the DLL. One difference in source code is that a DLL can contain a DllMain function.
The DllMain function is called whenever an application loads or unloads the DLL. This action
provides you with a mechanism to perform initializations when the DLL is first loaded, which is
similar to a constructor in C++, and to free system resources/cleanup when the DLL is unloaded,
which is similar to a destructor in C++. If you do not explicitly define a DllMain,
LabWindows/CVI creates a default one that does nothing.
The functions inside a DLL can either be internal to the DLL or callable from other modules. The
functions that are callable from other modules are said to be exported from the DLL. To create the
DLL properly, the compiler must know which functions to export. In LabWindows/CVI, create a
header file containing the prototypes of the functions you want to export from the DLL. Add this
header file to the project. When a program uses a DLL, it can access only the functions or variables
that the DLL exports. The DLL can export only globally declared functions and variables. The
DLL cannot export functions and variables you declare as static. In the Target Settings dialog box,
you select from a list of all the include files in the project. The include file method does not work
with other compilers. However, it is similar to the .def method that some other compilers use.
LabWindows/CVI creates the DLL and the appropriate import library for that DLL, and this import
library must be linked to any program that calls the functions exported from the DLL.
4-6
ni.com
Lesson 4
Calling Conventions
What are calling conventions for functions?
How do you specify a calling convention?
Terms to know
__stdcall
__cdecl
DLLSTDCALL
Calling Conventions
When functions are called from your program, the arguments of the function are placed on the stack
in a particular order. In addition, either the calling program or the function itself is responsible for
cleaning up the stack. To set up this order and cleaning role, use a calling convention within your
function declaration. If you intend for only C or C++ programs to use your DLL, you can use the
__cdecl calling convention for the functions you want to export. If you want your DLL to be
callable from programs written in Microsoft Visual Basic or Pascal, you must declare the functions
you want to export with the __stdcall calling convention. You must explicitly define functions
with the __stdcall keyword (notice the double underscore __ in front of the words) whether or
not you choose to make __stdcall the default calling convention for your project. You must use
the __stdcall keyword in the declarations in the include file you distribute with the DLL. Other
platforms, such as Windows 3.1, do not recognize the __stdcall keyword. If you work with
source code that you might use on other platforms, use a macro in place of __stdcall. The macro
translates to the appropriate calling convention. The cvidef.h include file defines the
DLLSTDCALL macro for this purpose. The following example code uses the DLLSTDCALL macro.
int DLLSTDCALL MyIntFunc (void);
char * DLLSTDCALL MyStringFunc (void);
4-7
Lesson 4
Using DLLs
Link in the import library
Call functions as prototyped in the header
Put the DLL in the Windows system folder or in the current
project folder
Program
module1
Import Library
module2
DLL
Header
Using DLLs
When you use the functions of a DLL in one of your programs, you must add the import library to
your project so that it gets linked into the program. You also must call the functions in the DLL
according to the prototypes in the DLL header file, which you can accomplish by #including the
header file into the modules from which the functions are called. Place the DLL in the Windows
system folder or the folder in which the project exists, so that the DLL can be located and loaded
at run time.
4-8
ni.com
Lesson 4
Exercise 4-1
OBJECTIVE
4-9
Lesson 4
Exercise 4-1
Objective:
3. Create a new source file. Enter the following code or copy and paste the
code from firstdll.c in the C:\Solutions\CVI Basics II\
Exercise 4-1 directory.
4-10
ni.com
Lesson 4
4-11
Lesson 4
8. Click the Import Library Choices button. In the DLL Import Library
Choices dialog box, select Generate import libraries for both
compilers and click OK.
When you select this option, LabWindows/CVI creates import libraries
for both supported compilers in subdirectories under the projects root.
4-12
ni.com
Lesson 4
By default, the DLL and import libraries created have the same base
name as the project. In this case, firstdll.dll is created along with
three copies of firstdll.lib, the import library.
LabWindows/CVI always creates one import library in the same
directory as the DLL. That import library is created with the current
compatibility mode, Visual C++. Import libraries for both supported
compilers also are created and stored in their respective subdirectories
(msvc and borland). If you want to distribute this DLL and you know
which compiler your DLL will be used with, then you need to ship the
DLL, the header file, and the import library for that particular compiler.
13. Click OK in the LabWindows/CVI message, save any changes, and
close all open windows except the Workspace window.
4-13
Lesson 4
Exercise 4-2
OBJECTIVE
4-14
ni.com
Lesson 4
Exercise 4-2
Objective:
3. Save the file as testdll.c and add the file to the project.
4. Add the import library to the project so that the function can be resolved.
In the Workspace window, select EditAdd Files to ProjectLibrary
(*.lib). In the Add Files to Project dialog box, select firstdll.lib.
Click Add and then click OK.
5. Run the project. Four message pop-ups appear.
6. Return to the Source window and add the following bolded lines to the
code:
#include "firstdll.h"
void fnInternal(void);
main()
{
fnInternal();
fnDLLTest();
}
7. Recall that fnInternal was not exported when you created the DLL.
Therefore, when you try to run the project, you get an "Undefined
symbol" error when the project is linked.
8. Close testdll.c. Do not save any changes.
4-15
Lesson 4
Run a LabWindows/CVI project that calls the DLL. In this case, the DLL project is not open.
Open the DLL project and run an external process that uses the DLL.
To debug a DLL that another LabWindows/CVI project uses, you must run the project with the
debugging level set to a value other than none. When LabWindows/CVI loads the DLL, it loads the
corresponding debug information from the auxiliary debug files. LabWindows/CVI honors the
breakpoints you set in DLL source files. LabWindows/CVI saves in the project any breakpoints you
set in source files, regardless of whether the source file is in the project. You also can set watch
expressions for a debuggable DLL. For each watch expression, you must choose whether the watch
expression applies to a project or a DLL. If the watch expression applies to a DLL, you must enter
the name of the DLL. LabWindows/CVI stores this information in the project.
4-16
ni.com
Lesson 4
To debug a DLL that an external process uses, load the DLL project into LabWindows/CVI. Make
sure you set the debugging level to a value other than none. Select RunSpecify External Process.
A dialog box appears in which you enter the pathname and command line arguments to an external
program. LabWindows/CVI stores this information in the project. The RunRun Project
command changes to Debug xxx.exe, where xxx.exe is the filename of the external program.
When you execute the Debug xxx.exe command, LabWindows/CVI starts the external process and
attaches to it for debugging. If you have set any breakpoints in the source files for the DLL,
LabWindows/CVI honors them. If the external process loads other debuggable DLLs, you can
debug them even though the project for a different DLL is open.
4-17
Lesson 4
Exercise 4-3
OBJECTIVE
4-18
ni.com
Lesson 4
Exercise 4-3
Objective:
4-19
Lesson 4
Try adding watch expressions for other variables and see the different
settings applicable for variables defined in DLLs.
10. After testing the different DLL debugging features, close all files.
4-20
ni.com
Lesson 4
DLL Recommendations
Use DLLSTDCALL
Use the include file method
Avoid exporting variables. Use functions to set/get the
values of variables
Debug your DLL code as much as possible before creating
the DLL. Use DLL debugging to debug run-time problems.
DLL Recommendations
To simplify DLL creation, use the following recommendations:
Use the DLLSTDCALL macro in the declaration and definition of all functions you want to
export. Do not export functions with a variable number of arguments.
Identify the symbols you want to export using the include file method. Do not use export
qualifiers. If you use an external compiler, use the .def file method.
Do not export variables from the DLL. For each variable you want to export, create functions
to get and set the variable value or create a function that returns a pointer to the variable. Do
not use import qualifiers in the include file.
You can distribute with your DLL the same include file that you include in the source files you
use to make the DLL. This distribution is especially useful when you create DLLs from
instrument drivers.
You can use the same source code to create the DLL in LabWindows/CVI and both of the
compatible external compilers.
You can use your DLL in Microsoft Visual Basic or other non-C environments.
4-21
Lesson 4
4-22
ni.com
Lesson 4
cvisupp.libstartup library
cvirt.liblibrary related to User Interface, Formatting and I/O, RS-232, DDE Support,
4-23
Lesson 4
You can add the analysis.lib static library file, which contains the Analysis (or Advanced
Analysis) Library, from C:\Program Files\National Instruments\CVI\extlib
directory to your external compiler project.
4-24
ni.com
Lesson 4
nidaqmx.libNI-DAQmx Library
visa.libVISA Library
nivxi.libVXI Library
ivi.libIVI Library
cviauto.libActiveX Library
The cvirt.lib library file contains symbols for all the LabWindows/CVI libraries, except the
ANSI C Library. When you create an executable or DLL in an external compiler, you use the
compilers own ANSI C standard library. Because of this, you must use the external compilers
include files for the ANSI C library when compiling source files. Although the include files for the
other LabWindows/CVI libraries are in the C:\Program Files\National Instruments\
CVI\include directory, the LabWindows/CVI ANSI C include files are in the C:\Program
Files\National Instruments\CVI\include\ansi directory. Thus, you can specify
C:\Program Files\National Instruments\CVI\include as an include path in your
external compiler while, at the same time, using the external compilers version of the ANSI C
include files.
4-25
Lesson 4
One effect of using the external compilers ANSI C standard library is that the printf and scanf
functions do not use the LabWindows/CVI Standard Input/Output window. To use printf and
scanf, you must create a console application. To continue using the LabWindows/CVI Standard
Input/Output window, call the FmtOut and ScanIn functions in the Formatting and I/O Library.
4-26
ni.com
Lesson 4
CVI\include
CVI\sdk\include
4-27
Lesson 4
CVI\include
CVI\include\ansi
CVI\sdk\include
LabWindows/CVI does not work with all non-ANSI extensions each external compiler provides.
Also, in cases where ANSI does not specify the exact implementation, LabWindows/CVI does not
always agree with external compilers. Most of these differences are unclear and rarely encountered.
Refer to the Programmer Reference section in the LabWindows/CVI Help for details.
C++ Name Decoration
Use extern "C" {/* definitions in source code */ } to prevent C++ compilers/linkers
from decorating symbol names. Doing so allows for portability of code that might be linked in a
C or C++ compiler/linker. The following code is an example:
#ifdef __cplusplus
extern "C" {
#endif
/* Definitions in the Source Code*/
#ifdef __cplusplus
4-28
ni.com
Lesson 4
}
#endif
4-29
Lesson 4
4-30
ni.com
Lesson 4
When you pass the DLL module handle to LoadPanelEx and LoadMenuBarEx, the User
Interface Library searches the table of callback functions the DLL contains before searching the
table that the executable contains.
In summary, if you want to use LabWindows/CVI user interface features in an external compiler,
you must create the user interface resource in LabWindows/CVI. You can then write your callback
functions within a LabWindows/CVI DLL or you can write them inside an external compiler. If
you take the latter approach, you must include the UIR Callbacks object file.
4-31
Lesson 4
OBJECTIVE
4-32
ni.com
Lesson 4
Exercise 4-4
Objective:
To create an object file containing UIR callback support for use in an external
compiler.
Note This exercise requires that you use the Borland external compiler. To import a
LabWindows/CVI project into Microsoft Visual C++, choose the NI Measurement
Studio AppWizard when you create a new project in Measurement Studio. This utility
provides the option to automatically convert LabWindows/CVI programs, applications,
and libraries into Microsoft Visual C++ applications.
4-33
Lesson 4
4-34
ni.com
Lesson 4
10. After creating the file, close all windows except the Workspace window.
4-35
Lesson 4
OBJECTIVE
4-36
ni.com
Lesson 4
Exercise 4-5
Objective:
4-37
Lesson 4
Save this file as exportme.h. Add it to the project and close the
window.
10. In the Workspace window, select BuildTarget Settings.
11. Click the Import Library Choices button. In the DLL Import Library
Choices dialog box, select Generate import libraries for both
compilers and click OK. Selecting this option creates import libraries
for both supported compilers in subdirectories under the projects root.
12. Click the Change button in the Exports section. In the DLL Export
Options dialog box, check exportme.h, then click OK.
LabWindows/CVI uses this header file to determine what functions
to export.
13. Click OK to exit the Target Settings dialog box.
14. Select BuildConfigurationRelease.
15. To create the DLL, select BuildCreate Release Dynamic Link Library.
4-38
ni.com
Lesson 4
Summary Lesson 4
Use DLLs to add modularity to your programming
design
You can create and use DLLs from within
LabWindows/CVI
DLL debugging is available for DLLs created in
LabWindows/CVI
Understand the issues underlying the porting of code
between compilers
Summary Lesson 4
In this lesson, you learned about DLLs and the issues regarding the porting of code between
compilers.
Because a DLL is compiled code, follow the recommendations stated in the lesson when creating
a DLL. When troubleshooting programs, you can usually trace the source of the problem to a DLL.
For example, if you use a particular calling convention in your project and your DLL has a different
calling convention, the program might not function.
If you have only the header file for the DLL and not the import library, you can
generate the import library from the header file. Select OptionsGenerate DLL Import
Library when you open the header file.
Note
When porting code between development environments, make sure that if you use
LabWindows/CVI functions, you include the necessary header files, libraries (static or import), and
the LabWindows/CVI Run-Time Engine. Refer to the Programmer Reference section of the
LabWindows/CVI Help for information about portability and compatibility.
4-39
Lesson 4
Notes
4-40
ni.com
Additional Topics
Lesson 5: Additional Topics
A. Multithreaded programming
B. Integrating the Windows Platform SDK
C. Useful utility functions
Introduction
This lesson covers the following topics, which extend the core functionality of LabWindows/CVI.
Using the Platform SDK to add power and flexibility to your LabWindows/CVI application
Using miscellaneous utility functions for memory access, error handling, and handling
executables
This lesson also covers several advanced programming topics that can be optionally covered for the
individual needs of LabWindows/CVI users.
5-1
Lesson 5
Additional Topics
Multithreading Terms
Multitasking
Multiple executables running concurrently
Preemptive versus non-preemptive
Multithreading
Multiple threads in a single executable
Multiprocessor machines
Multiple processors (CPUs) in a machine
Multithreading Terms
MultitaskingMultiple executables run at the same time. For example, you can download a
file using FTP while you edit a document in a word processing program.
5-2
ni.com
Lesson 5
Additional Topics
Multithreaded Programs
T
I
M
Word
Processor
Process
UI
Printing
Thread 1
Thread 2
E
Program
Multithreaded Programs
The large box represents a single process. The smaller boxes represent a single thread of execution.
From the user perspective, the UI responds to user input while the program is printing. On
multiprocessor machines or fast machines, the user might not be able to see a degradation of UI
responsiveness while a print operation is running.
5-3
Lesson 5
Additional Topics
Benefits of Multithreading
Keep time-critical tasks from being greatly affected by UI
Keep UI responsive while performing command in
background
Printing in background
Benefits of Multithreading
The reliability of your data acquisition or control can increase by executing the data acquisition or
control in one thread while the UI executes in another thread.
You can execute lengthy operations in a spawned thread so that the main application thread always
can respond to UI events.
You can implement algorithms so that different pieces of the algorithm execute in separate threads.
If an algorithm that is implemented in such a manner is executed on a machine with multiple
processors, the algorithm executes faster than a traditional, single-threaded implementation of the
algorithm. A classic example is a compiler implemented in such a way that the preprocessor runs
in one thread and the actual compile runs in another thread, which results in improved throughput.
A more efficient implementation is a program in which independent pieces of the program run in
separate threads. For example, a TCP server application that responds to multiple clients is easier
to write if each client is handled by a separate thread in the server application.
5-4
ni.com
Lesson 5
Additional Topics
Multithreading in LabWindows/CVI
Thread Pool
Thread creation
Thread Safe Queue
Passing data safely between multiple threads
Thread Safe Variables
Protecting data used in multiple threads
Thread Lock
Critical section or mutex in C
Prevents multiple access of data
Thread Local Variables
Per thread values for variables
Note: All threading functions are in Utility Library
Multithreading in LabWindows/CVI
With thread pools, you can schedule functions for execution in separate threads. Thread pools
handle thread caching to minimize the overhead associated with creating and destroying threads.
Thread safe queues abstract passing data between threads. One thread can read from a queue at the
same time that another thread writes to the queue.
Thread safe variables effectively combine a critical section and an arbitrary data type. You can call
a single function to acquire the critical section, set the variable value, and release the critical
section.
Thread lock simplifies using a critical section or mutex by providing a consistent API and using
the appropriate mechanism when necessary. For example, a mutex is used if the lock needs to be
shared between processes or if threads need to process messages while waiting for the lock. A
critical section is used in other cases because it is more efficient.
Thread local variables provide per-thread instances of variables. The operating system places a
limitation on the number of thread local variables available to each process. The LabWindows/CVI
implementation consolidates the thread local variables, using only one process thread local variable
for all of the thread local variables in your program. You can find all of the multithreading functions
in the LabWindows/CVI Library Tree under Utility LibraryMultithreading.
5-5
Lesson 5
Additional Topics
Thread Pools
Thread pools manage groups of threads
Programs have a default thread pool
Max threads = 2 + 2*NumberOfProcessors
Thread Pools
Thread pools are the mechanism for creating and managing threads in LabWindows/CVI.
LabWindows/CVI applications have one default thread pool. For many cases, creating additional
thread pools is unnecessary, and you can use the default thread pool instead. The default thread pool
can hold a maximum of 2 + 2*(NumberOfProcessors) threads, which translates into a maximum
of 4 threads for single processor machines and 6 threads for dual processor machines. If you need
more threads than the one that fits in the default thread pool, you can create an additional thread
pool. You also might want to create additional thread pools to group threads that have logical
connections. For example, you can use one thread pool for all data acquisition threads.
Creating thread pools does not create any actual threads. Threads are created by scheduling
functions in the thread pool with the CmtScheduleThreadPoolFunction. Functions that are
scheduled in threads can be named by anything. However, they must have a specific function
prototype:
int CVICALLBACK FuncName (void *functionData);
5-6
ni.com
Lesson 5
Additional Topics
Application
Default Thread Pool
1. Run program
2. Schedule function
func1 in default
thread pool
3. Create second
thread pool
4. Schedule function
func2 in second thread
pool
main()
thread
func1()
thread
When a function is scheduled in the default thread pool, the default thread pool is initialized and
the function begins running in a separate thread. In this case you can use the CmtNewThreadPool
function to create a second thread pool. CmtNewThreadPool returns a handle to the new thread
pool that you can use to schedule functions. Another function, func2, can be scheduled in the
second thread pool and begins running in another thread. This second thread pool must be
discarded in the program when it is no longer needed or when the program exits. To discard the
second thread pool, use CmtDiscardThreadPool.
5-7
Lesson 5
Additional Topics
...
CmtScheduleThreadPoolFunction
(DEFAULT_THREAD_POOL_HANDLE, func1, NULL,
&func1ID);
CmtNewThreadPool (4, &poolHandle);
CmtScheduleThreadPoolFunction (poolHandle,
func2, NULL, &func2ID);
5-8
ni.com
Lesson 5
Additional Topics
Exercise 5-1
OBJECTIVE
5-9
Lesson 5
Additional Topics
Exercise 5-1
Objective:
Multithreading in LabWindows/CVI
MAXTHREADS
&poolHandle
After you complete the function panel, select CodeInsert Function Call to
insert the function call into your source code.
Note
5-10
ni.com
Lesson 5
Additional Topics
Note The default thread pool is not used because more threads are needed than are
available in the default thread pool.
4. The NewThread callback function is called when you click the Create
Thread button. This function checks to see if the maximum number of
threads (MAXTHREADS) has been reached. The NewThread function
instantiates a new control and places the control on the panel.
MyThreadFunction, which has already been written, updates the
control. You need to write code to create and schedule a thread that runs
the MyThreadFunction function. Navigate to the /* Schedule new
thread function here */ comment in the NewThread function
and insert a function call to the CmtScheduleThreadPoolFunction
below the comment to create a new thread. From the Library Tree, select
Utility LibraryMultithreadingThread PoolCall Scheduling
FunctionsCmtScheduleThreadPoolFunction and complete the
function panel as shown in the following table.
Pool Handle
Thread Function
Thread Function Data
Thread Function ID
poolHandle
MyThreadFunction
(void *)ctrlID
NULL
5. Add the following line to increment the numThreads variable below the
CmtScheduleThreadPoolFunction. This keeps track of how many
threads have been allocated.
numThreads++;
6. Navigate to the Quit callback function. This function shuts down all of
the threads and causes the program to stop executing. Enter exiting =
1; below the /* Discard thread pool here and set exiting
flag */ comment to stop the threads. After setting the exiting flag,
select Utility LibraryMultithreadingThread PoolAdvanced
FunctionsCmtDiscardThreadPool from the Library Tree and pass
poolHandle as the Pool Handle parameter. Insert the
CmtDiscardThreadPool function into the Source window.
7. Examine the thread function, MyThreadFunction. Notice how the
function uses the exiting flag to exit the function.
8. Build and run the project. Verify that the Create Thread button works
properly. As more threads are added, notice that they continue to run.
Also notice how the speed of each thread decreases as more threads
are created.
5-11
Lesson 5
Additional Topics
5-12
ni.com
Lesson 5
Additional Topics
Read Level
TSQ
5-13
Lesson 5
Additional Topics
Exercise 5-2
OBJECTIVE
5-14
ni.com
Lesson 5
Exercise 5-2
Objective:
Additional Topics
Note Notice that creating a thread pool was not mentioned in the preceding steps.
The DEFAULT_THREAD_POOL that is created by LabWindows/CVI can contain up to
2 + 2 * (number of processors in computer) threads. In most computers with only
one processor there can be four threads running at any time. Most of the time it is not
necessary to create a new thread pool if the application requires only two or three threads.
If you do not know in advance how many threads the application will require, then it is a
good idea to create a new thread pool.
5-15
Lesson 5
Additional Topics
5-16
ni.com
Lesson 5
Additional Topics
In the main function place your cursor below the /* Create Thread
Safe Queue */ comment. Insert the CmtNewTSQ function under the
comment to create a new thread safe queue before starting the user
interface. From the Library Tree, select Utility Library
MultithreadingThread Safe QueueGeneral Functions
CmtNewTSQ and complete the function panel as shown in the
following table.
Number of Items
Item Size
Options
Queue Handle
QUEUE_SIZE
sizeof(double)
0
&TSQHandle
Note After you complete the function panel, select CodeInsert Function Call to
insert the function call into your source code.
Use the constant QUEUE_SIZE for the number of items in the queue.
The queue holds double values, so the item size is sizeof(double).
Use the global variable TSQHandle, which is already declared in
tsq.c, for the thread safe queue handle.
5-17
Lesson 5
Additional Topics
TSQHandle
Event
Event Threshold Value
Callback Function
Callback Data
Callback Thread ID
Items in Queue
Callback ID
50
ReadDataFromTSQ
&callbackID
CmtGetCurrentThreadID()
&callbackID
This function installs the thread safe queue event callback function so
that when 50 items are in the queue, the ReadDataFromTSQ function is
called.
4. Place your cursor below the /* Uninstall the thread safe
queue callback function */ comment. Insert the
CmtUninstallTSQCallback function under the comment. From the
Library Tree, select Utility LibraryMultithreadingThread Safe
QueueCallbacksCmtUninstallTSQCallback and complete the
function panel as shown in the following table. Then, insert the function
call in the code.
Queue Handle
Callback ID
TSQHandle
callbackID
TSQHandle
5-18
ni.com
Lesson 5
Additional Topics
1. All of the code to determine if the thread is running has already been
written. It is always good practice to write code that checks to make sure
that the maximum number of threads for the application has not been
reached in the code that schedules the thread. Place your cursor below
the /* Create new thread to generate data by scheduling
function */ comment. Insert the
CmtScheduleThreadPoolFunction function under the comment.
From the Library Tree, select Utility LibraryMultithreading
ThreadPoolCall Scheduling Functions
CmtScheduleThreadPoolFunction and complete the function panel as
shown in the following table.
Pool Handle
Thread Function
Thread Function Data
Thread Function ID
DEFAULT_THREAD_POOL_HANDLE
SimulateData
&threadID
&threadID
5-19
Lesson 5
Additional Topics
1. The code for the function has already been written. This function creates
a random number that specifies the length of the sine wave to generate.
The only thing that you must do is send the sine data from the thread to
the main calling application. Remember that this data is critical data and
must be protected. Place your cursor below the /* Add the data in
the write buffer to the thread-safe queue */ comment.
Insert the CmtWriteTSQData function under the comment. From the
Library Tree, select Utility LibraryMultithreadingThread Safe
QueueReading/WritingCmtWriteTSQData and complete the
function panel as shown in the following table.
Queue Handle
Buffer
Number of Items
Timeout(ms)
Number of Items Flushed
TSQHandle
writeBuffer
numItemsInWriteBuffer
TSQ_INFINITE_TIMEOUT
NULL
5-20
ni.com
Lesson 5
Additional Topics
This function has already been written for you. Notice that the function
alternates between plot colors of red and blue each time the event function
is called. It is necessary to determine how many items are in the queue. This
is accomplished using the CmtGetTSQAttribute function. If an error
occurs, this function returns a negative number. CmtReadTSQData reads
the data from the queue. Notice how the function dynamically allocates an
array to store the data items from the queue.
5-21
Lesson 5
Additional Topics
DEFAULT_THREAD_POOL_HANDLE
Thread Function ID
Options
threadID
0
2. After the thread finishes executing, you can unschedule the thread
function from the thread pool. Insert the
CmtReleaseThreadPoolFunctionID function below the
CmtWaitForThreadPoolFunctionCompletion function. From the
Library Tree, select Utility LibraryMultithreadingThread Pool
Call Scheduling FunctionsCmtReleaseThreadPoolFunctionID and
complete the function panel as shown in the following table.
Pool Handle
Thread Function ID
5-22
DEFAULT_THREAD_POOL_HANDLE
threadID
ni.com
Lesson 5
Additional Topics
Part F: Run
Save and run the program. Verify that the Start, Stop, and Quit buttons
work properly. Notice how the rate of data going to the strip chart changes
while the simulation is running. This action occurs because the data
simulation thread sends random sizes of data to the thread safe queue.
Notice that the application is passing data from the thread to the main
application to display the data on the strip chart. The data that is generated
in the SimulateData function will not get corrupted with the use of thread
safe queues.
5-23
Lesson 5
Additional Topics
Well-Behaved Applications
Well-Behaved Applications
If you spend much time inside a callback function, then periodically call ProcessSystemEvents
or ProcessDrawEvents. ProcessSystemEvents allows LabWindows/CVI to check if other
events, such as Windows messages, are waiting to be processed. ProcessDrawEvents updates
the user interface only. Refer to the messaging section of Lesson 1.
Use PostDeferredCall to execute functions after your callback has ended. The function does
not execute until the next call to GetUserEvent, RunUserInterface, or
ProcessSystemEvents.
5-24
ni.com
Lesson 5
Additional Topics
5-25
Lesson 5
Additional Topics
5-26
ni.com
Lesson 5
Additional Topics
Additional Functions
I/O and
Memory
Access
Using
Executables
Useful
Utilities
Creating
Well-Behaved
Applications
Error
Handling
Additional Functions
This lesson discusses additional functions that are useful for certain types of LabWindows/CVI
applications. However, many other functions are beyond the scope of this course. For these
functions, refer to the function panel help, help in the LabWindows/CVI Help, or the
LabWindows/CVI examples.
5-27
Lesson 5
Additional Topics
0x378
outp
MapPhysicalMemory
pointer
UnMapPhysicalMemory
I/O Space To communicate in I/O space, use the inp and outp functions. For example, to
perform any type of parallel port communication, you must use these functions. For these
functions, you should know the exact address to read from and write to.
Memory SpaceTo read from and write to physical memory, use
ReadFromPhysicalMemory and WriteToPhysicalMemory, respectively. You can use
extended versions of these functions to specify the actual byte transfer size. Every time you use
these functions, you are mapping and unmapping physical memory. To reduce this overhead,
use the MapPhysicalMemory/UnMapPhysicalMemory functions to obtain pointers to
portions of memory. You can treat these pointers like any other C pointers, incrementing and
manipulating objects in a familiar manner.
When you use Windows 2000/XP, these functions require you to load a low-level
support driver, cvintdrv.sys, that is shipped with LabWindows/CVI. The
LabWindows/CVI libraries automatically load the low-level support driver,
cvintdrv.sys, at startup if it is on disk. To ensure that the driver is loaded before you
proceed, call the CVILowLevelSupportDriverLoaded function at the beginning of
your program. To include the driver when creating your stand-alone executables, enable
the Low-Level Support Driver option in the Drivers & Components tab of the Edit
Installer dialog box.
Note
5-28
ni.com
Lesson 5
Additional Topics
5-29
Lesson 5
Additional Topics
5-30
ni.com
Lesson 5
Additional Topics
5-31
Lesson 5
Additional Topics
Error Handling
Library errors
SetBreakOnLibraryErrors
GetBreakOnLibraryErrors
Protection errors
SetBreakOnProtectionErrors
GetBreakOnProtectionErrors
Error Handling
LabWindows/CVI user protection allows the compiler to monitor all types of pointer
manipulations in your code and store data structures internally for each type. At run time,
LabWindows/CVI dynamically watches your pointer manipulations and informs you of illegal
accesses. LabWindows/CVI does the same action for simple out-of-bounds indexing of statically
declared arrays and more complex series of dynamic allocations with malloc, calloc, and so on.
With these user protection features, you do not need to spend time tracking down pointer bugs,
which are typically some of the most difficult bugs to find. LabWindows/CVI displays a run-time
dialog box that lists any instances of illegal access due to an out-of-bounds pointer or an attempt
to free an invalid pointer and highlights the erroneous line in your code. You can configure
LabWindows/CVI to display a run-time error dialog box and suspend execution when an NI library
function reports an error. To enable this type of debugging, select RunBreak onLibrary Errors
or use the Utility Library SetBreakOnLibraryErrors/GetBreakOnLibraryErrors
functions. You also can work around user protection errors flagged by LabWindows/CVI by using
the SetBreakOnProtectionErrors/GetBreakOnProtectionErrors functions. Normally,
you apply these functions around a small section of code as a workaround to some pointer problems
you have coded into your program.
LabWindows/CVI keeps track of all library function calls and watches all pointer accesses as it
executes your program and informs you when it detects an error. When you do not perform a debug
build, these features are disabled.
5-32
ni.com
Lesson 5
Additional Topics
Sleep More
Do Not Sleep
checks an event from the operating system, it can put itself in the background, in sleep mode, for
a specified period of time. While LabWindows/CVI is in sleep mode, other applications have more
processor time. The disadvantage of increasing the amount your application sleeps is that your
application responds slightly slower to events.
To view or change the current LabWindows/CVI sleep policy, select OptionsEnvironment.
CVI environment sleep policyYou can specify how much LabWindows/CVI sleeps by
selecting one of the following sleep policy choices:
Do not sleep
Sleep some
Sleep more
You also can view or change the sleep policy programmatically by calling either
GetSleepPolicy or SetSleepPolicy. By using SetSleepPolicy, you might free some
CPU use.
The figure above demonstrates the effect of the sleep policy on a Windows XP system. Changes in
sleep policy have different effects depending on the operating system. Experiment with the various
sleep options for your particular application. Increase the sleep mode if you want to free processor
usage and decrease the sleep mode if you want LabWindows/CVI to poll the user interface faster
for user events.
5-33
Lesson 5
Additional Topics
Additional Functionality
Use <Ctrl-Shift-P>, Find Function Panel, to search for
functions based on keywords
Check out the built-in LabWindows/CVI instrument drivers
in the C:\Program Files\National
Instruments\CVI\toolslib directory
Increase your Windows programming skills with the
Windows SDK functions
Additional Functionality
Because of the large number of functions and utilities within LabWindows/CVI, it is important that
you know how to find the functions you need to complete or refine your application.
In the Source window, use the ViewFind Function Panel command (<Ctrl-Shift-P>) to search
for functions based solely on keywords. Remember to use a variety of synonyms, because the
function might be spelled differently than you expected.
LabWindows/CVI includes functionality through its built-in instrument drivers. As you learned in
this course, LabWindows/CVI provides many drivers for custom controls but also provides several
miscellaneous functions in the toolbox instrument driver. You can supplement the built-in
instrument drivers by purchasing add-on toolkits. Currently, you can purchase toolkits for SQL
(database manipulation), TX (test function management), SPC (statistical process control), IMAQ
(image processing), PID (process control for automation), and INET (internet).
If a function does not exist, you can create the function through Windows SDK. Creating a function
using the Windows SDK requires that you have some knowledge of Windows programming.
5-34
ni.com
Lesson 5
Additional Topics
Toolkits
Enhance LabWindows/CVI through add-on toolkits:
TestStandtest management
SQLdatabase manipulation
PIDfeedback control
IMAQimage processing
Toolkits
As a stand-alone package, LabWindows/CVI includes a wealth of features. However, you can
enhance LabWindows/CVI with toolkits that include functions for specific business applications.
These toolkits are sold as separate packages because they include functionality that not all
LabWindows/CVI programmers need.
TestStand
TestStand is a ready-to-run, customizable test executive used in automated test environments. A
test executive relieves test engineers from worrying about the repetitive tasks of test program
management, such as logging test results to file and handling multiple levels of users. TestStand
allows a test engineering group to spend the bulk of its time on one specialized
purposedeveloping test functions.
SQL ToolkitInterfacing with Databases
With the Structured Query Language (SQL toolkit) LabWindows/CVI programs can manipulate
database files. Use the SQL toolkit to do basic database functions, such as creating, fetching, and
sorting records.
PID Toolkit
PID, Proportional-Integral-Derivative is a defined control strategy standard used in industry.
The PID toolkit is an instrument driver with functions to access the process parameters associated
with PID algorithms.
IMAQ Vision
IMAQ Vision is an add-on package for adding image processing and machine vision features to
your applications.
5-35
Lesson 5
Additional Topics
Toolkits (cont.)
Enhance LabWindows/CVI through add-on toolkits:
Motion Controlmotion sequencing
SPCstatistical process control
Signal Processing Toolsetsignal processing and
spectral analysis
Toolkits (cont.)
Motion Control
The Motion Control Module for LabWindows/CVI provides an interactive development
environment for motion sequencing. The Motion Control Module integrates with NI vision, data
acquisition, and instrument control software and hardware.
SPC Toolkit
The SPC Toolkit contains functions to determine the statistics necessary for process
controldeviation, control limits, ranges, process capability.
Signal Processing Toolset
The Signal Processing Toolset is a software package that gives users ready-to-run, stand-alone
signal processing capabilities and developers high-level digital signal processing (DSP) tools and
utilities. The toolset provides four toolkits for digital filter design, joint time-frequency analysis,
wavelet and filter bank design, and super-resolution, model-based spectral analysis.
You can access all LabWindows/CVI toolkits through instrument drivers. Instrument drivers are
general tools for hiding low-level complexity, not just for controlling stand-alone instruments.
Though you purchase toolkits in addition to the LabWindows/CVI package, toolkits actually
reduce development costs. Before you start developing your application, calculate the time you
would spend creating the basic functionality that might already exist in the toolkits. Development
time builds quickly. In addition, the maintenance costs of in-house development are higher than
buying tools that you can customize.
5-36
ni.com
Lesson 5
Additional Topics
Note There might be licensing issues regarding toolkits if you want to distribute
applications that use them.
5-37
Lesson 5
Additional Topics
Summary Lesson 5
This lesson describes a wide variety of topics about the powerful
set of LabWindows/CVI features.
Multithreaded Programmingusing the threading tools of
LabWindows/CVI to create efficient programs
Platform SDKadding the power of Windows
programming to LabWindows/CVI
Utility functionsuncovering the depth of
LabWindows/CVI functions
Summary Lesson 5
This lesson describes an assortment of features that extend the basic functionality of
LabWindows/CVI.
To develop programs that take advantage of multiprocessor machines and can do multiple functions
at once, break the program into multiple threads using functions in the Multithreading class of the
Utility Library.
If you cannot find a particular way to accomplish an objective using LabWindows/CVI libraries,
you can integrate the Platform SDK into your applications.
The Utility Library provides several functions to meet specialized needs, such as handling
executables.
5-38
ni.com
Lesson 5
Additional Topics
LabWindows/CVI Publications
LabWindows/CVI Programming for Beginners by Shahid F. Khalid
Advanced Topics in LabWindows/CVI by Shahid F. Khalid
LabWindows/CVI Publications
The books listed in the figure above are just a few of the publications written about
LabWindows/CVI programming and applications. The National Instruments Web site contains a
list of all the LabWindows/CVI books and links to locations where you can purchase these books.
5-39
Lesson 5
Additional Topics
5-40
ni.com
Lesson 5
Additional Topics
Notes
5-41
Lesson 5
Additional Topics
Notes
5-42
ni.com
A-1
Appendix A
LabWindows/CVI Resources
This section describes how you can receive more information regarding
LabWindows/CVI.
A-2
ni.com
Course Evaluation
Course _______________________________________________________________________________________
Location _____________________________________________________________________________________
Instructor _________________________________________
Date ____________________________________
Company _________________________________________
Instructor
Please evaluate the instructor by checking the appropriate circle.
Unsatisfactory Poor
Satisfactory Good
Excellent
Course
Training facility quality
Training equipment quality
Was the hardware set up correctly?
The course length was
Yes
No
Yes
No
Sometimes
Yes No
Co-worker
Other _____________________________________________________________________________________